Как я могу получить разницу запросов? - PullRequest
0 голосов
/ 07 октября 2018
class PostTemplate(BaseModel):

    content = TextField(unique=True)


class VkGroup(BaseModel):

    group_id = IntegerField(unique=True)


class PostTemplateVkGroup(BaseModel):
    """
    http://charlesleifer.com/blog/a-tour-of-tagging-schemas-many-to-many-bitmaps-and-more/
    """
    group = ForeignKeyField(VkGroup)
    post_template = ForeignKeyField(PostTemplate)



def get_posted_templates_for_group(group_id: int) -> Iterable:
    """Get posted templates.

    Args:
        group_id (int): id группы
    """
    queries = (PostTemplate
               .select()
               .join(PostTemplateVkGroups)
               .join(VkGroup)
               .where(VkGroup.group_id == group_id))
    return queries

all_post_templates = PostTemplate.select()

Отношение «многие ко многим».
Для каждой записи в PostTemplateVkGroup шаблон записи из этой записи используется в группе из этой записи.

all_post_templates = not_posted_templates |Posted_templates

Как я могу получить not_posted_templates?

1 Ответ

0 голосов
/ 09 октября 2018

Если ваша база данных поддерживает операцию «ИСКЛЮЧИТЬ», вы можете:

all_post_templates = PostTemplate.alias().select()
post_templates = get_posted_templates_for_group(...)
difference = all_post_templates - post_templates

Пример Sqlite:

class Post(Base):
    title = TextField()

class Tag(Base):
    tag = TextField()

class PostTag(Base):
    post = ForeignKeyField(Post)
    tag = ForeignKeyField(Tag)

db.create_tables([Post, Tag, PostTag])
data = (
    ('pa', ('ta1', 'ta2')),
    ('pb', ('tb1', 'tb2')),
    ('pc', ()))
for title, tags in data:
    post = Post.create(title=title)
    for tag in tags:
        tag = Tag.create(tag=tag)
        PostTag.create(post=post, tag=tag)

# Create some tags that aren't associated with any post.
Tag.create(tag='tx1')
Tag.create(tag='tx2')

pa1_tags = (Tag
            .select()
            .join(PostTag)
            .join(Post)
            .where(Post.title == 'pa'))
all_tags = Tag.alias().select()
diff = all_tags - pa1_tags
for t in diff:
    print(t.tag)

# Prints
# tb1
# tb2
# tx1
# tx2
...