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?
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.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With