Django: How to filter using "not equals" and "or" case

One thing I loved about Django is its ease for writing reusable queries.

However, it didn't take long before I ran into the problem of "how do I do not equals?".

Take for example the SQL query:

SELECT * FROM model WHERE id != 3

To make that work in Django filters, we'd use the Q object.

from django.db.models import Q

YourModel.objects.get(~Q(id = 3))

Like in C++, the ~ will negate the operation.

The next issue I ran into was how to create the "OR" filter. Normally, chaining filters will use the "AND" operator which is sufficient for most queries in your system.

But sometimes you need the "OR", and with that Q comes to the rescue again.

Say for example, this time you want to this SQL query:

SELECT * FROM model WHERE (name LIKE "Montgomery" OR name LIKE "Smithers")

In Django using Q, it'd be written like:

YourModel.objects.get(Q(name = 'Montgomery') | Q(name = 'Smithers')

You can also mix up Q objects and keyword arguments, but you have to ensure that Q object filters are all defined BEFORE any keyword arguments. Refer to the documentation for a proper example of this.

[ Documentation ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog