1

let's say I have an Item model which is in a M2M relationship with Feature:

class Item(models.Model):
    features = models.ManyToManyField(to = 'Feature')

now I'd like to filter the Item queryset to include only the Items which has at least all the specified features.

Lets say that possible features are: Camera, Touchscreen, Keyboard

now I'd like to select all the Items which has both Camera and Keyboard

any solutions?

2 Answers 2

3

Assuming the Feature's model have a field called "name", you can filter the items matching that field in a list of values. Something like this would work:

Item.objects.filter(features__name__in=['Camera', 'Touchscreen', 'Keyboard'])

UPDATE:

As stalk says here, to get the items that match all the features you need to do many "filters" to the query. A way to get it dynamically is:

features = ['Camera', 'Touchscreen', 'Keyboard']
items = Item.objects.all()

for feature in features:
  items = items.filter(feature__name=feature)

This way you can pass a dynamic list of features to match items.

4
  • 2
    This query will return all Items, that have at least one feature from provided list. And question was "I'd like to select all the Items which has both Camera and Keyboard". So, the query must be Item.objects.filter(features__name='Camera').filter(features__name='Keyboard')
    – stalk
    Apr 26, 2013 at 15:43
  • well, multiple filtering is an option to go, however it is a bit tricky, and - when filtering agains many features, will cause the query string to grow significantly. I'm considering to filter it python-side ..
    – migajek
    Apr 26, 2013 at 16:11
  • If you filter using python you'll need to get each related object from the db, and this will increase the number of queries. Instead, using filter (any number of times) will create just one query to the db because of QuerySet are lazy as you can read here: docs.djangoproject.com/en/dev/topics/db/queries/…
    – Darwin
    Apr 26, 2013 at 16:14
  • for each "feature" to be filtered with, there is one more JOIN. I'm afraid of sql performance when there are like 50 features ;)
    – migajek
    Apr 26, 2013 at 18:23
1

If your feature model uses a name field then this should work:

Items.objects.filter(features__name='Camera', features__name='Keyboard')

Edit: Syntax error in above query. Should be 2 filters chained together:

Items.objects.filter(features__name='Camera').filter(features_name='Keyboard')
1
  • this is agains Python syntax, you're repeating the keyword argument. however the double-filtering (Item.objects.filter(..).filter(..) ) works as expected. This however is a bit tricky, looking for a cleaner way ;)
    – migajek
    Apr 26, 2013 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.