[英]django model manytomany filter
Lets say I have User, Newsletter and Subscription models, Subscription is the mapping table for User and Newsletter, eg. 假设我有User,Newsletter和Subscription模型,Subscription是User和Newsletter的映射表。 Subscription has foreign key to User and Newsletter
订阅具有用户和通讯的外键
class User(models.Model):
...
class Newsletter(models.Model):
...
class Subscription(models.Model):
subscriber = models.ForeignKey(User)
newsletter = models.ForeignKey(Newsletter)
How do I get the query set that returns Newsletter that a particular user has subscribed to in a very simple query? 如何在非常简单的查询中获取返回特定用户已订阅的新闻通讯的查询集? I feel there is one, but can't really think of it unless going through multiple statements to achieve this.
我觉得有一个,但是除非经过多条语句才能实现,否则无法真正想到。
This should work: 这应该工作:
Newsletter.objects.filter(
id__in=[subscription.newsletter.id for subscription in
Subscription.objects.filter(subscriber=user)]
More readable(and verbose) version: 更具可读性(和冗长)的版本:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.