Underoos
Underoos

Reputation: 5190

How to convert datetimefield to string in Django values_list() function?

I have a model which contains a datetime field. I need to write the rows from that model table to excel sheet.

As the model field is datetime field, when writing to the excel, it's writing a number like 45976 etc for dates instead of 2020-04-01 as string.

I'm getting values of rows using queryset.values_list(*fields_to_fetch) This fields_to_fetch contains the datetimefield I'm looking for. When I print the type, it is saying DateTimeField in the console.

Is there any way to get the datetimefield as string type?

I was able to convert each item in the values_list() to list and then the datetimefield into string and append it to a new list and write to excel.

I'm looking for a way to avoid all this.

Upvotes: 1

Views: 1129

Answers (1)

JPG
JPG

Reputation: 88509

Use Cast(...) database function,

from django.db.models.functions import Cast
from django.db.models import CharField

cast_expr = Cast('date_time_field', output_field=CharField())
data = ModelKlass.objects.annotate(dt_as_str=cast_expr).values_list('dt_as_str')

Upvotes: 4

Related Questions