113π
(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?
169π
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.
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
- [Django]-Set Django's FileField to an existing file
17π
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β.
- [Django]-Django model constraint for related objects
- [Django]-How to upload a file in Django?
- [Django]-How to change a django QueryDict to Python Dict?
3π
You can use AND
with filter() using &
or Q() and &
as shown below:
# "store/views.py"
from .models import Question
from django.db.models import Q
from django.http import HttpResponse
def test(request):
# With "&"
# β Here
qs = Question.objects.filter(question__contains="software") & \
Question.objects.filter(question__contains="java")
print(qs)
# With "Q()" and "&"
# β Here # β Here
qs = Question.objects.filter(Q(question__contains="software") &
Q(question__contains="java"))
print(qs) # β Here
return HttpResponse("Test")
- [Django]-How do you know if memcached is doing anything?
- [Django]-Heroku, postgreSQL, django, comments, tastypie: No operator matches the given name and argument type(s). You might need to add explicit type casts
- [Django]-Django's SuspiciousOperation Invalid HTTP_HOST header