django模型manytomany过滤器

时间:2013-02-07 02:20:02

标签: python django filter

假设我有User,Newsletter和Subscription模型,Subscription是User和Newsletter的映射表,例如。订阅具有用户和简报的外键

class User(models.Model):
  ...

class Newsletter(models.Model):
  ...

class Subscription(models.Model):
  subscriber = models.ForeignKey(User)
  newsletter = models.ForeignKey(Newsletter)

如何获取返回特定用户在非常简单的查询中订阅的新闻稿的查询集?我觉得有一个,但除非通过多个陈述来实现这一点,否则无法真正想到它。

1 个答案:

答案 0 :(得分:1)

这应该有效:

Newsletter.objects.filter(
    id__in=[subscription.newsletter.id for subscription in
            Subscription.objects.filter(subscriber=user)]

更易阅读(和详细)版本:

subscriptions = Subscription.objects.filter(subscriber=user) # all subscriptions for a given user

newsletter_ids = [subscription.newsletter.id for subscription in subscriptions]

Newsletter.objects.filter(id__in=newsletter_ids) # answer