tags:

views:

376

answers:

3

How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.

For example the following SQL query does exactly that when I run it on mysql database:

select * from myapp_question
where ((question like '%software%') and (question like '%java%'))

How do you accomplish this in Django using filters?

+9  A: 
mymodel.objects.filter(first_name__icontains="Foo", first_name__icontains="Bar")
Andrea Di Persio
+2  A: 

You can chain filter expressions in Django:

q = Question.objects.filter(question__contains='software').filter(question__contains='java')

You can find more info in the Django docs at "Chaining Filters".

mipadi
+7  A: 

For thoroughness sake, let's just mention the Q object method:

from django.db.models import Q
criterion1 = Q(question__contains="software")
criterion2 = Q(question__contains="java")
q = Question.objects.filter(criterion1 & criterion2)

Note the other answers here are simpler and better adapted for your use case, but if anyone with a similar but slightly more complex problem (such as needing "not" or "or") sees this, it's good to have the reference right here.

David Berger
Very interesting!
Andrea Di Persio