在ManyToManyField中间表字段上进行过滤

4 投票
2 回答
2026 浏览
提问于 2025-04-17 20:08

我有一个常见的多对多关系(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)

我想要获取一个查询集,里面包含某个客户的所有商品,并且这些商品的数量要大于0。到目前为止,我找到的唯一方法(来自这里)是先过滤中间表,然后用Python代码生成一个对象列表,但我需要的是一个查询集(用于一个表单的ChoiceField)。

2 个回答

2

这是什么意思呢?

Customer.object.filter(customeritem__item_count__gt=0)
9

这里 -

items = Item.objects.filter(customer_items__customer=customer, customer_items__item_count__gt = 0)

因为你在Item的外键上加了related_name='customer_items',所以你可以通过item.customer_items来访问与任何Item相关的CustomerItem。剩下的事情就简单了。

撰写回答