【发布时间】:2013-03-14 01:23:39
【问题描述】:
我有一个普通的 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, related_name='customer_items')
customer = models.ForeignKey(Customer, related_name='customer_items')
item_count = models.PositiveIntegerField(default=0)
我想获得一个查询集,其中包含给定客户的所有项目,其中item_count > 0。到目前为止,我发现的唯一方法(来自here)是过滤中间表,然后使用 Python 代码制作对象列表,但我需要一个查询集(用于ChoiceField 的表单)。
【问题讨论】:
-
items = Item.objects.filter(customer_items__customer=customer, customer_items__item_count__gt = 0)工作吗? -
@Bibhas 似乎工作,请写一个答案
标签: python django many-to-many django-orm