how to get list of objects involving many to many

2019-04-06 02:05发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-06 02:41

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

查看更多
登录 后发表回答