Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to construct django Q object matching none

I wonder which is the correct way to construct a Q(...) object which matches no object in the queryset. It seems that both Q() and ~Q() match all objects!

like image 937
Emanuele Paolini Avatar asked Apr 27 '15 15:04

Emanuele Paolini


People also ask

What is Django Q OBJECT and how to use it?

What is Django Q Object and How we can use it in our application simple guide Django uses Object Relational Mapper for the querying database. It’s good for most cases, but sometimes, you need to run more complex queries. For that, the Django ORM ship with Q objects and it can construct more complex database queries.

What is the best database query engine for Django?

Django uses Object Relational Mapper for the querying database. It’s good for most cases, but sometimes, you need to run more complex queries. For that, the Django ORM ship with Q objects and it can construct more complex database queries. At the very beginning, when I study the Django material, I find it very hard to follow the docs.

What is object relational mapper in Django?

Django uses Object Relational Mapper for the querying database. It’s good for most cases, but sometimes, you need to run more complex queries. For that, the Django ORM ship with Q objects and it can construct more complex database queries.

How do I create a queryset in Django?

Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters. For example, our application has a Book model with a few basic fields: title, author, and date_published.


2 Answers

Q(pk__in=[]) should do the trick.

like image 116
akaariai Avatar answered Sep 21 '22 06:09

akaariai


Q(pk=None) works fine.

Q(pk__in=[]) works fine as well and doesn't hit the database.

like image 26
Sven R. Kunze Avatar answered Sep 20 '22 06:09

Sven R. Kunze