djangodjango-modelsdjango-managers

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


class SupercalifragilisticexpialidociousManager(models.Manager):
    # Sorry, I'm sick of Foo and Spam for now.
    def get_query_set(self, account=None):
        return super(SupercalifragilisticexpialidociousManager,
                     self).get_query_set().filter(uncle=model_thats_using_this_manager_instance.uncle)

The magic I'm looking for is the "uncle=model_thats_using_this_manager_instance.uncle". It seems like I should be able to do this somehow. I know I could say self.model to get the model, but how to get the instance?


Solution

  • 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.