Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does declaring a manager to a Django model, void "objects"

I have declared a manager to the following model, but after doing so, I can no longer use List.objects.get(). Anybody know why?

class List(models.Model):
  title = models.CharField(max_length=20, unique=True)
  archived = models.BooleanField()

  archived_lists = ArchivedListManager()
  active_lists = ActiveListManager()

And the managers:

class ArchivedListManager(models.Manager):
  def get_query_set(self):
    return super(ArchivedListManager, self).get_query_set().filter(archived=True)

class ActiveListManager(models.Manager):
  def get_query_set(self):
    return super(ActiveListManager, self).get_query_set().filter(archived=False)

The error is type object 'List' has no attribute 'objects'

like image 845
Josh Avatar asked Dec 15 '10 21:12

Josh


1 Answers

As noted in the Django docs:

If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they're defined in the model) has a special status. Django interprets the first Manager defined in a class as the "default" Manager, and several parts of Django will use that Manager exclusively for that model. As a result, it's a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_query_set() results in an inability to retrieve objects you'd like to work with.

So as far as "why" goes, it's to allow you to provide your own default manager.

The solution is simple, though: just add this

objects = models.Manager()

to your model class.

like image 150
mipadi Avatar answered Oct 09 '22 11:10

mipadi