Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading