Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do an OR filter in a Django query?

I want to be able to list the items that either a user has added (they are listed as the creator) or the item has been approved.

So I basically need to select:

item.creator = owner or item.moderated = False 

How would I do this in Django? (preferably with a filter or queryset).

like image 928
Mez Avatar asked Apr 11 '09 09:04

Mez


People also ask

What is __ In Django filter?

filter(tags__in=tags) matches photos that have any of the tags, not only those that has all. Some of those that only has one of the desired tags, may have exactly the amount of tags that you are looking for, and some of those that has all the desired tags, may also have additional tags.

How can I filter a Django query with a list of values?

To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .

What are Q objects Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django. db.

How do I create a complex query in Django?

Your complex query require a subquery in the principle. Possible solutions are: A subquery written by 'extra' queryset method or raw SQL query. It is not DRY and it was unsupported by some db backends, e.g. by some versions of MySQL, however subqueries are by some limited way used since Django 1.1.


1 Answers

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)) 
like image 178
Alex Koshelev Avatar answered Oct 22 '22 03:10

Alex Koshelev