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 ?
You can do this with a custom model manager and override the get_query_set
function to always filter canceled=False.
class CustomManager(models.Manager):
def get_query_set(self):
return super(CustomManager, self).get_query_set().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()
.
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.