Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override .objects on a django model?

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?

like image 866
willcritchlow Avatar asked Jan 21 '11 18:01

willcritchlow


1 Answers

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.

like image 171
ars Avatar answered Sep 20 '22 14:09

ars