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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With