Python 筛选多个ManyToManyField中间表字段
我有一个普通的M2M,中间表中有一个附加字段:Python 筛选多个ManyToManyField中间表字段,python,django,many-to-many,django-orm,Python,Django,Many To Many,Django Orm,我有一个普通的M2M,中间表中有一个附加字段: class Customer(models.Model): items = models.ManyToManyField(Item, verbose_name=u'Items', through='CustomerItem') class Item(models.Model): pass class CustomerItem(models.Model): item = models.ForeignKey(Item, re
class Customer(models.Model):
items = models.ManyToManyField(Item, verbose_name=u'Items', through='CustomerItem')
class Item(models.Model):
pass
class CustomerItem(models.Model):
item = models.ForeignKey(Item, related_name='customer_items')
customer = models.ForeignKey(Customer, related_name='customer_items')
item_count = models.PositiveIntegerField(default=0)
我想获得一个包含给定客户所有项目的查询集,其中item\u count>0
。到目前为止,我找到的唯一方法(从)是过滤中间表,然后用Python代码生成对象列表,但我需要一个查询集(用于表单ChoiceField
)
Customer.object.filter(customeritem__item_count__gt=0)
这里-
items = Item.objects.filter(customer_items__customer=customer, customer_items__item_count__gt = 0)
当您将
相关的\u name='customer\u项目'
添加到项目
外键时。您可以通过Item.customer\u items
访问与任何项目相关的CustomerItem
。剩下的就是小菜一碟。是否items=Item.objects.filter(customer\u items\u customer=customer,customer\u items\u Item\u count\u gt=0)
起作用?@Bibhas似乎起作用了,请写一个答案