wRA*_*RAR 2 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, related_name='customer_items')
customer = models.ForeignKey(Customer, related_name='customer_items')
item_count = models.PositiveIntegerField(default=0)
Run Code Online (Sandbox Code Playgroud)
我想获得一个查询集,其中包含给定客户的所有项目item_count > 0.我到目前为止找到的唯一方法(从这里开始)是过滤中间表,然后用Python代码创建一个对象列表,但我需要一个查询集(用于表单ChoiceField).
这里 -
items = Item.objects.filter(customer_items__customer=customer, customer_items__item_count__gt = 0)
Run Code Online (Sandbox Code Playgroud)
正如你已经添加related_name='customer_items'到Item外键.您可以访问CustomerItem与任何Item通行证相关的内容item.customer_items.休息是小菜一碟.
| 归档时间: |
|
| 查看次数: |
1212 次 |
| 最近记录: |