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

时间:2021-07-23 20:17:06

I have the following models:

我有以下型号:

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)

I need to get all of the Items that belong to all of the commitees in which a user is connected through the CommitteeRole.

我需要通过委员会获得属于用户所连接的所有委员的所有项目。

Something like this:

像这样的东西:

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

How can I accomplish this?

我怎么能做到这一点?

1 个解决方案

#1


14  

Actually, you have already accomplished it (Almost):

实际上,你已经完成了它(几乎):

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

And, if you are looking for a single query, you can try this:

而且,如果您要查找单个查询,可以尝试以下方法:

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

Documentation here and here

文档在这里和这里

#1


14  

Actually, you have already accomplished it (Almost):

实际上,你已经完成了它(几乎):

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

And, if you are looking for a single query, you can try this:

而且,如果您要查找单个查询,可以尝试以下方法:

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

Documentation here and here

文档在这里和这里