conversion of datetime Field to string in django queryset.values_list()

后端 未结 8 1871
南方客
南方客 2020-12-06 09:29

I have a queryset like:

qs = MyModel.objects.filter(name=\'me\').values_list(\'activation_date\')

here activation_date is

8条回答
  •  不知归路
    2020-12-06 09:57

    Very surprised to see that no one suggested the cast to a simple TextField (note, I'm using Postgres so I can't confirm for other RDBMSes):

    queryset = FooBarModel.objects.values(my_datetime=Cast('some_datetime_field', TextField()))
    foo_bar = queryset.first()
    foo_bar['my_datetime']
    >>> u'2019-10-03 17:59:37.979578+00'
    

    It similarly also works fine for nested fields:

    queryset = FooBarModel.objects.values(Cast('baz__some_datetime_field', TextField()))
    

    Alternatively, a custom Func can also be used (also specific to Postgres here, but can be modified for any other RDBMS):

    class FullDateTimeCast(Func):
       """
       Coerce an expression to a new field type.
       """
       function = 'TO_CHAR'
       template = '%(function)s(%(expressions)s, \'FMDay, Month DD, YYYY at HH12:MI:SS AM\')'
    
    queryset = FooBarModel.objects.values(my_datetime=FullDateTimeCast('some_datetime_field', TextField()))
    foo_bar = queryset.first()
    foo_bar['my_datetime']
    >>> u' Thursday, October 03, 2019 at 17:59:37 PM'
    

提交回复
热议问题