Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a request.user to a model Manager?

I have a model manager with a get_queryset:

class BookManager(models.Manager):

    def get_queryset(self):

        return super().get_queryset().filter(author=self.request.user

This results in the error:

AttributeError: 'BookManager' object has no attribute 'request`

I understand managers are "request-unaware". How would I make a method in your manager/queryset that takes a parameter for the request.user?

like image 324
alias51 Avatar asked Oct 28 '25 05:10

alias51


1 Answers

Short answer: The request object is only available in a view, so you can't assume it's available in your model manager.

Pass it from your view to a method in your manager that accepts it:

class BookManager(models.Manager):
    def by_author(self, user):
        return self.get_queryset().filter(author=user)

Then in your view you can do Book.objects.by_author(request.user). You'd need to make sure first that request.user is a logged in user otherwise you'll get an exception.

Note: In this particular case I wouldn't go through the trouble of defining by_author since it hardly makes your code more readable. But if there are more complex queries that you often need, then it might make sense to assign them a method in your manager to create DRY code.

like image 53
dirkgroten Avatar answered Oct 30 '25 01:10

dirkgroten