wRAR
wRAR

Reputation: 25693

Filter on ManyToManyField intermediate table fields

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).

Upvotes: 4

Views: 2090

Answers (2)

Bibhas Debnath
Bibhas Debnath

Reputation: 14929

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.

Upvotes: 9

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

what about this?

Customer.object.filter(customeritem__item_count__gt=0)

Upvotes: 2

Related Questions