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?
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()