Question

Normally I'd access the queryset via SomeModel.objects().

I notice that inside the model, the objects is defined to be some Manager, like, objects=SomeManager().

So, if I'm defining a method inside a Manager, how would I access objects?

As in...

class SomeManager(models.Manager):
    def some_method(self):
        ( HOW WOULD I ACCESS OBJECTS HERE? )

class SomeModel(models.Model):
    ... blah blah
    objects=SomeManager()

If I wanted to filter something, I suppose I could do SomeModel.objects.filter inside the manager, but somehow that feels weird. Would it be something like self.filter or something?

Was it helpful?

Solution

Yes, you would just use self.filter, where 'self' refers to the Manager itself. The default Manager for the model is objects, and it is automatically created if you don't specify a custom manager. Because you a doing a custom manager, you don't use objects, because obviously that would use the default one, and not your custom one.

So, from the Docs, an example would be:

class BookManager(models.Manager):
    def title_count(self, keyword):
        return self.filter(title__icontains=keyword).count()

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
    num_pages = models.IntegerField(blank=True, null=True)
    objects = BookManager()

OTHER TIPS

Short answer: You don't access the manager from within itself. There is no need since you have access to all of the methods via self

objects is the manager in this case. Since you normally use the manager to access things like filter and get you can access them locally on the class using self.filter or self.get.

If you need to have something like select_related applied to every queryset returned by the manager, you can override the get_queryset method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top