I have an usual M2M with an additional field in the intermediate table:
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)
I want to get a queryset with all Items for a given Customer where item_count > 0
. The only way I've found so far (from here) is to filter the intermediate table and then make a list of objects with Python code, but I need a queryset (for a form ChoiceField
).
Here -
items = Item.objects.filter(customer_items__customer=customer, customer_items__item_count__gt = 0)
As you've added related_name='customer_items'
to the Item
foreign-key. You can access the CustomerItem
related to any Item
via item.customer_items
. Rest is piece of cake.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With