我有以下型号:
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)
我该如何做到这一点?
答案 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)