2

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.

1 Answer 1

5

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')
Sign up to request clarification or add additional context in comments.

8 Comments

In the annotate, I want to assign the cast_expression to same field name in my model and it's raising conflict for that. Is there any workaround for this?
you can't do that
Or Is there any way to get the elements as list instead of tuple in values_list()?
I don;t understand that, can you explain bit more?
When I use values_list(), each element in that list is of type tuple. Can I get each element as list instead of tuple. Is there any parameter that I can pass to values_list()?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.