Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM extract weekday as string from queryset

What I'm trying to do is annotate a queryset with the weekday strings ("monday", "tuesday" etc).

I understand how to get the int values:

queryset = queryset.annotate(
  weekday_int=ExtractWeekDay("date"),
)

But I'm having trouble getting the string values themselves. I've tried using an ExpressionWrapper, but F objects don't seem to play well with Date objects.

I'm using postgres as my underlying database but can't find a related lookup_name for the generic Extract.

like image 331
Darkstarone Avatar asked Jul 21 '26 13:07

Darkstarone


1 Answers

I've tested this:

import calendar


class ExtractWeekDayName(ExtractWeekDay):
    @property
    def output_field(self):
        return CharField()

    def convert_value(self, value, expression, connection, context):
        v = super(ExtractWeekDayName, self).convert_value(value, expression, connection)
        try:
            return calendar.day_name[int(v)].lower()
        except (ValueError, IndexError):
            return 'error'
        except TypeError: # NoneType
            return ''

Seems legit.

like image 56
Andrey Nelubin Avatar answered Jul 24 '26 08:07

Andrey Nelubin