0

假设我有 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)

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

4

1 回答 1

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
于 2013-02-07T02:29:51.073 回答