migajek
migajek

Reputation: 8614

Django: filter queryset by intersection result

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?

Upvotes: 1

Views: 2483

Answers (2)

Robert Lee Murrer III
Robert Lee Murrer III

Reputation: 53

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

Upvotes: 1

Darwin
Darwin

Reputation: 1859

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.

Upvotes: 3

Related Questions