Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify default queryset in django

I have added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ?

like image 420
juanefren Avatar asked Mar 22 '10 17:03

juanefren


People also ask

How do I override QuerySet in Django?

To override default queryset in Python Django admin, we can override the get_queryset method in our model. to add the get_queryset into MyModelAdmin . In it, we call call the super constructor with MyModelAdmin and self . And we get the queryset wirth get_queryset from the super class.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is BASE user manager Django?

A Manager is a Django class that provides the interface between database query operations and a Django model. In other words, in a Django model, the manager is the interface that interacts with the database.


2 Answers

You can do this with a custom model manager and override the get_queryset function to always filter canceled=False.

class CustomManager(models.Manager):     def get_queryset(self):         return super().get_queryset().filter(canceled=False)  class MyModel(models.Model):     # Blah blah     objects = CustomManager() 

Then when calling MyModel.objects.all() it will always exclude canceled objects. Here is a blog post I found helpful on the subject. http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/

EDIT: Perhaps a better approach with a custom manager would be to attach it to another property, other than objects, such as:

class MyModel(models.Model):     # Blah blah     active = CustomManager() 

And in your views your queries would look like MyModel.active.all().

EDIT2: Updated method spelling from get_query_set to get_queryset for modern versions of django.

like image 90
Mark Lavin Avatar answered Sep 24 '22 15:09

Mark Lavin


You could write custom query manager, but I don't believe this is the right way to go. This would make an implicit, hidden condition for a filter, which would make code unreadable. Remember Zen of Python: Explicit is better than implicit. Detect places, where you need to add cancelled=False and just add this, that's the way you should do this.

like image 41
gruszczy Avatar answered Sep 22 '22 15:09

gruszczy