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

后端 未结 8 1856
南方客
南方客 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:56

    extra is deprecated in Django 2.0

    That's why I think the best solution to get a stringified datetime is:

    foo_bar = FooBarModel.objects.annotate(
        str_datetime=Cast(
            TruncSecond('some_datetime_field', DateTimeField()), CharField()
        )
    ).values('str_datetime').first()
    

    The result is:

    foo_bar.str_datetime:
    (str)'2014-03-28 15:36:55'
    

    Also I'd like to mention that you can format it as well in any way you want like:

    from django.db.models import Value
    
    foo_bar = FooBarModel.objects.annotate(
        day=Cast(ExtractDay('some_datetime_field'), CharField()),
        hour=Cast(ExtractHour('some_datetime_field'), CharField()),
        str_datetime=Concat(
            Value('Days: '), 'day', Value(' Hours: '), 'hour', 
            output_field=CharField()
        )
    ).values('str_datetime').first()
    

    The result is:

    foo_bar.str_datetime:
    (str)'Days: 28 Hours: 15'
    

提交回复
热议问题