如何在django中获取涉及多对多关系的对象列表

时间:2013-09-15 19:34:53

标签: django django-models django-orm

我有以下型号:

class Committee(models.Model):
    customer = models.ForeignKey(Customer, related_name="committees")
    name = models.CharField(max_length=255)
    members = models.ManyToManyField(member, through=CommitteeMember, related_name="committees")
    items = models.ManyToManyField(Item, related_name="committees", blank=True)

class CommitteeRole(models.Model):
    committee = models.ForeignKey('Committee')
    member = models.ForeignKey(member)
    #user is the members user/user number
    user = models.ForeignKey(User)
    role = models.IntegerField(choices=ROLES, default=0)

class Member(models.Model):
    customer = models.ForeignKey(Customer, related_name='members')
    name = models.CharField(max_length=255)

class Item(models.Model):
    customer = models.ForeignKey(Customer, related_name="items")
    name = models.CharField(max_length=255)

class Customer(models.Model):
    user = models.OneToOneField(User, related_name="customer")
    name = models.CharField(max_length=255)

我需要通过CommitteeRole获取属于用户所连接的所有委托人的所有项目。

这样的事情:

committee_relations = CommitteeRole.objects.filter(user=request.user)
item_list = Item.objects.filter(committees=committee_relations__committee)

我该如何做到这一点?

1 个答案:

答案 0 :(得分:16)

实际上,你已经完成了它(差不多):

committee_relations = CommitteeRole.objects.filter(user=request.user).values_list('committee__pk', flat=True)
item_list = Item.objects.filter(committees__in=committee_relations)

而且,如果您正在寻找单个查询,可以试试这个:

items = Item.objects.filter(customer__committees__committeerole__user=request.user)

文档herehere