Search code examples
pythonsqldjangodjango-ormdjango-filter

How to use "AND" in a Django filter?


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?


Solution

  • (update: this answer will not work anymore and give the syntax error keyword argument repeated)

    mymodel.objects.filter(first_name__icontains="Foo", first_name__icontains="Bar")
    

    update: Long time since I wrote this answer and done some django, but I am sure to this days the best approach is to use the Q object method like David Berger shows here: How do I use AND in a Django filter?