djangopostgresqldjango-orm

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.


Solution

  • 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.