简体   繁体   中英

How to filter a Django query set by passing in a list of options?

I've got an abstract ProductAttribute model that can be associated with a Product model. The attributes can be accessed using product.attribute_values.

Say I've got a form which contains two select boxes that allow the user to specify the values of two attributes - Size and Weight.

How do I, in a single query, pass in those values into a filter, so that - as you can with a list of integers with Object.objects.filter(pk__in=(1,2,3)) - I can select the Product that matches against all those attribute values?

I'd like to be able to do something like:

options = ['XL','50lbs']
p = Product.objects.filter(attribute_values__matches=options)

Is this possible in a one-liner in Django?

TIA

You can use __contains or __exact

and for case insensitive matches __icontains and __iexact

You can use Q model lookups to do an and filtering:

options = ['X1', 'X2', 'X3']
qs = [Q(attribute_name=option) for option in options] #or attribute_name__icontains - or whatever

query = qs.pop() #get the first element

for q in qs:
    query |= q

qs = MyModel.objects.filter(query)

I ended up cracking this one with a little help from @karthikr above, and the the Q.add() method:

options = {'Size':'XL'}
qs = Q()
for key, val in options.iteritems():
qs.add(Q(attributes__name=key) & Q(attribute_values__value_option__option=val), qs.connector)

Hope this helps someone else in some small way in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM