E
E
Egegey2021-07-13 17:31:34
Django
Egegey, 2021-07-13 17:31:34

Can an annotated field be assigned not a simple value (str, int, False, ...), but a model object?

class Chat(models.Model):

    def last_message(self):
        return self.messages.last()

class Message(models.Model):
        chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name='messages')
        text = models.TextField()


I'm trying to get rid of the "last_message" method so that querying all chats doesn't poll the base for each chat.
Is it possible to add an annotated field (and replace the method) so that it contains the message object?

The maximum that I could do was fix "prefetch_related" for the chat:
Chat.objects.prefetch_related(Prefetch('messages', queryset=last_messages)

The variable 'last_messages' stores a queryset consisting of one object - the last message.
But still, to get it, you need to make a request to the database.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question