11

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?

willcritchlow
  • 721
  • 3
  • 7
  • 18

1 Answers1

33

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.

creimers
  • 4,975
  • 4
  • 33
  • 55
ars
  • 120,335
  • 23
  • 147
  • 134
  • 1
    Completely right answer. Should be marked as correct @willcritchlow ! – Neneil Aug 31 '19 at 21:33
  • What about update the registers from `MyModel`? When I try to this I receive `object has no attribute 'bulk_update'` –  Nov 12 '19 at 21:41