Django Filter ManyToManyField Queryset

时间:2016-07-18 13:24:59

标签: django filter many-to-many

我有一个棘手的问题(我认为)

我有一个名为Post(models.Model)的模型:有多对多的关系称为共享

class Post(models.Model):
    account = models.ForeignKey(Account, related_name="account")
    shares = models.ManyToManyField(Account, related_name="shares_account", through='Share')
    ...

class Share(models.Model):
    post = models.ForeignKey(Post)
    account = models.ForeignKey(Account)

    new = models.BooleanField(default=True)
    ...

现在我需要一种方法来过滤具有精确" x"分享......例如。我有一个id" 222"此帖子与帐号ID 12,13,16共享。现在我想过滤所有与帐号ID为12,13和16共享的帖子。

我该怎么办? 我的糟糕尝试就是这样::;)

posts = Post.objects.filter(reduce(and_, [Q(shares=aid) for aid in account_ids]))

2 个答案:

答案 0 :(得分:0)

我想这对你有用。

pop

看到这个 - > Django ManyToMany filtering by set size or member in the set

答案 1 :(得分:0)

这是使用reduce

实现目标的方法
post_qs = Post.objects.all()
post_qs = reduce(lambda posts, share: posts.filter(shares=share), account_ids, post_qs)

我可能会以这种方式使其更具可重用性:

class PostQuerySet(models.QuerySet):

    def having_shares(self, share_ids):
        return reduce(lambda posts, share: posts.filter(shares=share), share_ids, self)

class Post(models.Model):
    ...

    objects = PostQuerySet.as_manager(


#usage
posts = Post.objects.all().having_shares(share_ids)