how to convert DateField field while returning a filtered result in DJANGO

Question:

I have the following table in django:

models.py

class Activity(models.Model)
  name = models.CharField(max_length=50)
  date_created = models.DateField()

here is the way i create an instance of that table

from datetime import date

Activity.objects.create(name="Foo", date_created=str(date.today()))

I know that auto_now_add=True can be used to store the date but at the moment it’s out of the question and I need to find a solution exactly like the models is above.

Is there a way to format the date_created field while querying all instances of the table Activity using .values() below in the views.py

views.py

activity = Activity.objects.filter(name="soccer").values()

I am currently getting the following error:

TypeError: Object of type date is not JSON serializable
activity = Activity.objects.filter(name="soccer").values()
Asked By: gerdo smith

||

Answers:

Pass the date object itself:

Activity.objects.create(name="Foo", date_created=date.today())

Is there a way to format the date_created field while querying all instances of the table Activity using .values() below in the views.py.

The format of a non-text objects is an implementation detail, nor is it the task of the database to format this. You should do this in the template, serializer, or view.

Furthermore using .values() is often not a good idea anyway. Django has a DjangoJSONEncoder [Django-doc] that will encode datetime with the ISO-8601 standard.

Answered By: Willem Van Onsem