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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With