Like if I have a Message model like
class Message(models.Model):
from = models.ForeignKey(User)
to = models.ManyToManyField(User)
def get_authenticated_user_inbox_messages(self):
return Message.objects.filter(to=authenticated_user).all()
authenticated_user being a way to get the currently authenticated user.
In the view, I can get the authenticated user with request.user
But, if I don’t want or can’t by design to pass this as a parameter, is there a way to get it directly from inside the model?
Any ideas? Thank you very much!
No, this is not possible. A Model object exists independently from a web request. For example, you can define a management command that uses model objects from the command-line, where there is no request.
What I’ve seen as a good practice is to define a static method on your Model object that takes a User object as input, like this:
You could also define a custom manager for the model and define these convenience methods there instead.
EDIT: Okay, technically it is possible, but I wouldn’t recommend doing it. For a method, see Global Django Requests.