Django first word of a char field

My model in django has a character field with maximum length 500 character. I'm working with a PostgreSQL database:

class Chat(models.Model):
    message = models.CharField(max_length=500)
    username = models.CharField(max_length=255)
    date = models.DateTimeField(auto_now_add=True)

    def first_word(self):
        return self.message.split(" ")[0]

I'm interested to evaluate first word of each message and do some aggregation. First word of each message could vary in length thus I can't use Left, Right or Substr database functions:

queryset = Chat.objects.annotate(command=F("first_word")).values("command")

Obviously my queryset is not working because I can't call model methods in database query. However is there a way I can do this by using some other database functions?

Back to Top