1

I'm using an F-expression to get a foreign key object's date value. But it returns a datetime object as the date. How can I transform it to 'YYYY-MM-DD' format?

from django.db.models import F

PendingRequest.objects.all().values('id', creation_date=F('agreement__created_at__date'))

output:
<QuerySet [
{'id': 1, 'creation_date': datetime.date(2022, 10, 16)},
{'id': 2, 'creation_date': datetime.date(2022, 10, 16)},
...
2

1 Answer 1

1

But it returns a datetime object as the date. How can I transform it to 'YYYY-MM-DD' format?

Please, don't use the database to format dates or strings. Databases should not be used to render data. Databases are used to store, retrieve and aggregate data.

It is the task of the templates, serializers, etc. to provide the data in an accessible format. For example in the template, you can format a date with the |date template filter [Django-doc]:

{{ my_date|date:"Y-m-d" }}

Django also can serialize data [Django-doc], if you serialize it to JSON, it will also encod it in that format:

>>> json.dumps(date(2023, 10, 20), cls=DjangoJSONEncoder)
'"2023-10-20"'
Sign up to request clarification or add additional context in comments.

Comments

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.