How do I do an OR filter in a Django query?
There is Q objects that allow to complex lookups. Example: from django.db.models import Q Item.objects.filter(Q(creator=owner) | Q(moderated=False))
There is Q objects that allow to complex lookups. Example: from django.db.models import Q Item.objects.filter(Q(creator=owner) | Q(moderated=False))
You could do this: Name.objects.exclude(alias__isnull=True) If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so: Name.objects.exclude(alias__isnull=True).exclude(alias__exact=””) Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, … Read more
Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost. from itertools import chain result_list = list(chain(page_list, article_list, post_list)) Using itertools.chain is faster than looping each list and appending elements one by … Read more
You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions: from myapp.models import Entry from django.db.models import Q Entry.objects.filter(~Q(id=3)) will return all entries except the one(s) with 3 as their ID: [<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, …]