Trying to add or to Q filter as method

Hey All -

I’m a total newbie at Django/Python and am wondering if someone could help direct me to how to add an OR operator to my filter here? I’ve looked through the documentation but the code i’m working with is setup as a method and not function so i’ve been a little lost.

I want to add languages__isnull=True to the following filter:

program_filters &= models.Q(languages__contains=[l.lower()])



The basic information for creating a logical OR condition in your query is covered in the Complex lookups with Q objects docs.

To provide accurate and more specific assistance, we’re probably going to need to see the entire method from which this fragment is taken. And, it may also be helpful if you provided a description of what this query is intended to return. (Or, if you’re more comfortable with SQL, you could provide the SELECT statement that you’re trying to replicate.)

Hey thanks for responding - the documentation uses a different syntax than the code i’m working with - it’s using Q() as a function, but i’m using Q() as a method.

This is what the documentation says:

    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))

Here’s my code:

from django.db import models
class SearchAppView(APIView):
    def get(self, request):
                languages = request.GET.getlist("programLanguages[]", None)
                program_filters = models.Q()
                if languages and len(languages):
                   for l in languages:
                      program_filters &= models.Q(languages__contains=[l.lower()])
                      # How do I add an OR operator above? languages__isnull=True

This is incorrect.

This is also incorrect.

Q is a class. In both cases you’re creating an instance of a Q object. The difference between the syntaxes is due to how the Q class is added to the current namespace within the module. There is no functional or semantic difference between the two.

Gotcha - so how would I add an OR operator using this different syntax?

As the documentation describes.

As I wrote before:

So this should work?

program_filters &= models.Q(languages__contains=[l.lower()]) | models.Q(languages__isnull=True)

Try it and see!

Getting into the habit of trying snippets like this in the Django shell (or shell_plus) is a very useful skill to develop.