tags:

views:

45

answers:

2

Say we have a dvd table where we want to search for price=14.99 and rating=18. We could do:

#Making some dictionary
dict1 = {}

#Adding some stuff
dict1['price']=14.99
dict1['rating']18

#Use dict as filter
dvd.objects.filter(**dict1)

Is there a way to add on extra parameters like:

dvd.objects.filter(title__icontains='the')

I'd just like to add a bit more flexibility for the user because at present they can choose what fields they'd like to search in and specify exactly what it is they want. However I'd like to search partial matches, like what __icontains does. I'd also like __gt, __lt.

Is this possible?

+1  A: 

I'm not sure what you want to do? Do you want to filter on additional fields after the initial dvd.objects.filter(**dict1)?? If so, you can simply do:

qs = dvd.objects.filter(**dict1)
qs.filter(title__icontains='the')

Remember, filter returns a queryset so you can perform any operations you want, just like you would on dvd.objects.

If, what you meant was you wanted to add icontains to something in dict, then you could simply assign the keys in dict1 as price__icontains instead of price.

Rishabh Manocha
+2  A: 

Instead of:

dict['price'] = 14.99

you can do something like this:

dict['price__gte'] = 10
dict['price__lte'] = 15

When you are using **kwargs the following are identical:

Model.objects.filter(price__gte=10, price__lte=15)
# or
kwargs = {'price__gte': 10,
          'price__lte': 15}      
Model.objects.filter(**kwargs)
sheats