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 ]

Android: Create a URL using Uri.Builder().build() with port numbers

Uri.Builder.build() works quite well with normal URLs, but it fails with port number support.

The easiest way that I discovered to make it support port numbers was to make it parse a given URL first then work with it.

Uri.Builder b = Uri.parse("http://www.yoursite.com:12345").buildUpon();

b.path("/path/to/something/");
b.appendQueryParameter("arg1", String.valueOf(42));

if (username != "") {
b.appendQueryParameter("username", username);
}

String url = b.build().toString();

And there you have it, a customisable URL with support for port number and queries.

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