[Django]-Django: How do you access a model's instance from inside a manager?

3👍

In methods like object.related_name.create() under the hood the Djangos sends a hint argument:

class UserQuerySet(QuerySet):
    def create(self, *args, **kwargs):
        print(self._hints)
        # >>> {'instance': <User: random-user>}
        print(self._hints.get('instance'))
        # >>> <User: random-user>

I’m using Django 1.11 nowadays.

7👍

It doesn’t make sense to ask for an instance when you’re using a manager. Managers are class-level attributes – if you try and do foo.objects.all() where foo is an instance of Supercalifragilisticexpialidocious, you will explicitly get an error:

AttributeError: Manager isn't accessible via Supercalifragilisticexpialidocious instances

4👍

As far as I know, you cannot access the model from inside a manager. It doesn’t make sense as managers operate on the whole table.

You should do something like this in the model:

class Model(models.Model):
    # some attributes here
    def getAllRelativesWithSameUncle(self):
        return Model.objects.filter(uncle = self.uncle)

or in the manager:

class SupercalifragilisticexpialidociousManager(models.Manager):
    def getSelfRelativesFor(self, model):
        return self.get_queryset().filter(uncle=model)

0👍

try self.model.

From the Docs

"Another thing to note is that Manager methods can access self.model to get the model class to which they’re attached." — https://docs.djangoproject.com/en/4.2/topics/db/managers/#adding-extra-manager-methods

What led to the answer: The manager knows what model to create when you call .create() from the manager.

Leave a comment