鉴于这是来自List的直通模型(我试图使用一些通用模型/字段,因为我的实际模型是行业特定的),
class List( models.Model ):
members = models.ManyToManyField( User, through='ListMembership')
...
class ListMembership( models.Model ):
member = models.ForeinKey( User )
list = models.ForeignKey( List )
member_accepted = models.BooleanField( default=False )
list_accepted = models.BooleanField( default=False )
...
我试图在List的查询集中使用through模型。我想获取当前登录用户所属的所有列表,并且被用户(member_accepted
)和列表(list_accepted
)接受。
如果我只关心成员并且不关心额外的模型字段,这将有效。
qs = List.objects.filter(members = self.request.user)
我想进入通过领域。
#this is wrong, but this gives an idea of what I am attempting to do
qs = List.objects.filter(members__through__member_accepted=True, members__through__list_accepted=True)
编辑以举例说明我不想做的事情
#this works, but I want to avoid the extra query
through_lists = ListMembership.objects.filter(member = request.user, member_accepted=True, list_accepted=True).values_list('list__pk', flat=True)
qs = List.objects.filter(pk__in=through_lists)
答案 0 :(得分:0)
这个应该真的有效:
qs = List.objects.filter(
members__member=request.user,
members__member_accepted=True,
members__list_accepted=True
)
请注意双下划线。
答案 1 :(得分:0)
through_lists = ListMembership.objects.filter(member = request.user, member_accepted=True, list_accepted=True)
然后在through_lists
中有ListMembership
个实例,只需获取每个实例的列表,无需额外查询。
lists = map(lambda x: x.list,through_lists)