I'd like to by default only return "published" instances (published=True). Is it possible to override .objects so that MyModel.objects.all() actually returns MyModel.objects.filter(published=True)?
Is this sensible? How would I get the unpublished ones in the rare cases where I did want them?
You can do this by writing a custom Manager -- just override the get_queryset
method and set your objects
to a Manager instance. For example:
class MyModelManager(models.Manager):
def get_queryset(self):
return super(MyModelManager, self).get_queryset().filter(published=True)
class MyModel(models.Model):
# fields
# ...
objects = MyModelManager()
See the docs for details. It's sensible if that's going to be your usual, default case. To get unpublished, create another manager which you can access with something like MyModel.unpublished_objects
. Again, the docs have examples on this type of thing.
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