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

后端 未结 8 1857
南方客
南方客 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条回答
  •  Happy的楠姐
    2020-12-06 09:41

    If you are using Postgres, you can do it like this (date format options here). The solution is database dependent, but it sure beats looping though a long list in Python land after your perform the query.

    qs = MyModel.objects.filter(name='me')
    qs = qs.extra(select={'datestr':"to_char(activation_date, 'YYYY-MM-DD HH24:MI:SS')"})
    qs = qs.values_list('datestr')
    

    I am sure MySQL has some equivalent function as Postgres's to_char, but you'll have to find that on your own as I am not a MySQL guy.

提交回复
热议问题