[Answered ]-Is there a way in Django to get the currently authenticated user directly from a model?

2👍

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:

class Message(models.Model):
    from = models.ForeignKey(User)
    to = models.ManyToManyField(User)

    @staticmethod
    def get_messages_to(user):
        return Message.objects.filter(to=user)

    @staticmethod
    def get_messages_from(user):
        return Message.objects.filter(from=user)

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.

0👍

When you connect the set up a foreign key from Messages to Users, django automatically creates a related field on the User model instances. (see https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects)

So, if you have a user object, you should be able to access user_object.messages.all(). This feels like a more django-appropriate way to do what your get_authenticated_user_inbox_messages() method is doing.

Leave a comment