Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use AND in a Django filter?

Tags:

python

django

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?

like image 556
gath Avatar asked Apr 20 '09 19:04

gath


People also ask

How do you use get and filter together in Django?

This exception is also an attribute of the model class. Returns a new QuerySet containing objects that match the given lookup parameters. Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters. Show activity on this post.

What is filter () in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How can I filter a Django query with a list of values?

To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .


1 Answers

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.

like image 170
David Berger Avatar answered Oct 10 '22 19:10

David Berger