1

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

G4bri3l
  • 4,996
  • 4
  • 31
  • 53
Cybran
  • 165
  • 1
  • 13
  • Create custom Encoder [documentation](https://docs.djangoproject.com/en/1.8/topics/serialization/#serialization-formats-json), if you using json api, perhaps better is using [django rest framework](http://www.django-rest-framework.org/) – i.krivosheev Jun 19 '15 at 08:42
  • @Wolkodav can you provide an example how can I create this? The docs example isn't as clear as it could be. – Cybran Jun 19 '15 at 08:53

1 Answers1

0

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)
Community
  • 1
  • 1
Caumons
  • 9,341
  • 14
  • 68
  • 82