How to change DateTime model field representation in serializer?

190 views Asked by At

I want to make a view that will return some model objects in JSON. Everything is ok exception made for DateTimeField, that serializes raw value, not as represented in the template. How can I get the pretty value rather than raw as shown below ?

Model:

class Request(models.Model):
    created_at = models.DateTimeField(auto_now=True)

Serialization:

serializers.serialize('json',
            list(Request.objects.filter(
                    id__gt=request.GET.get("last_id", 0)
                )[:MAX_REQUESTS])
        ),

Expected:

June 19, 2015, 8:24 a.m.

Result:

2015-06-19T08:23:18.021Z

1

There are 1 answers

0
Caumons On

You can return JSON serialized data with DateTime fields in ISO format, then from your javascript, you can parse and format the dates as you need. See: Help parsing ISO 8601 date in Javascript

import json

json.dumps(your_requests, default=lambda obj: obj.isoformat() if hasattr(obj, 'isoformat') else obj)