[Answered ]-Django – dynamic manager

2👍

This is not possible with a custom manager because a model manager is instantiated at class loading time. Hence, it is stateless with regard to the http-request-response cycle and could only provide some custom method that you would have to pass the user to anyway. So why don’t you just add some convenience method/property on your model (a manager seems unnecessary for this sole purpose)

class MyModel(models.Model):
    ...
    @clsmethod
    def user_objects(cls, user):
        return cls.objects.filter(owner=user.ownership)

Then, in your view:

objs = MyModel.user_objects(request.user)

For a manager-based solution, look at this question. Another interesting solution is a custom middleware that makes the current user available via some function/module attribute which can be accessed in acustom manager’s get_queryset() method, as described here.

Leave a comment