11

我有以下型号:

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)

我怎样才能做到这一点?

4

1 回答 1

19

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

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)

此处此处的文档

于 2013-09-15T19:38:37.917 回答