88

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?

4 Answers 4

168

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.

2
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?

11
  • 5
    This does not work for me in Django 1.6 and Postgres. I get a "SyntaxError: keyword argument repeated" whenever there are two or more the same keywords. Only the solution with Q by David Berger works. May 30, 2014 at 7:32
  • 1
    I have a model Country with a short country code field (cc_short): >>> countries = Country.objects.filter(cc_short__icontains='A', cc_short__icontains='B') File "<console>", line 1 SyntaxError: keyword argument repeated Jul 9, 2014 at 8:56
  • 1
    This also does not work for me either. Same error as @margusholland. Using Django 1.7.5. Code in question: talks = Talks.objects.filter(description__contains=topics,description__contains=terms).order_by('-datetime') Topics and terms are both lists.
    – Austin A
    Apr 21, 2015 at 20:37
  • 7
    Note that both fields are the same! It's python itself that doesn't allow this, it won't work in ANY django/db. This should not be an accepted answer.
    – rsalmei
    Jan 17, 2017 at 16:25
  • 1
    Hey @MayankMehtani, it should work if the keyword arguments themselves are different, not only their values.
    – rsalmei
    May 18, 2020 at 22:58
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".

6
  • 14
    This answer may give you wrong results depending on your scenario. Using , in filter vs chaining filters can have different results. Further reading : SO Answer & Official docs
    – user
    Jul 8, 2014 at 19:16
  • 1
    this is NOT answer for the asked question. It will give diff output. But this is what I was looking for. What OP wanted, allobjects.filter(name=x or name= y) but this answer will give first = allobjects.filter(name=x) then filter first.filter(name=y). Hope you guys get it. Sorry for pseudo code. Apr 18, 2020 at 18:44
  • 3
    @mohammed_ayaz The question asks for an AND operation, not an OR operation.
    – mipadi
    Apr 19, 2020 at 20:10
  • 1
    @Alexandru-MihaiManolescu: What has OR logic? This question is an AND, not an OR.
    – mipadi
    May 7, 2020 at 16:50
  • 1
    In OneToMany and M2M relations it should be used with caution, as it applies to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.
    – Amin Mir
    Jun 17, 2020 at 7:04
1

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")

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.