Last active
March 31, 2022 06:44
-
-
Save dannvix/29f53570dfde13f29c35 to your computer and use it in GitHub Desktop.
Custom Django JsonResponse which supports datetime.datetime serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# project/forum/views.py | |
import json | |
from datetime import datetime | |
from django.http import HttpResponse | |
from django.shortcuts import get_object_or_404 | |
from django.forms.models import model_to_dict | |
from forum.models import Post | |
class DateTimeEncoder(json.JSONEncoder): | |
# default JSONEncoder cannot serialize datetime.datetime objects | |
def default(self, obj): | |
if isinstance(obj, datetime): | |
encoded_object = obj.strftime('%s') | |
else: | |
encoded_object = super(self, obj) | |
return encoded_object | |
class JsonResponse(HttpResponse): | |
def __init__(self, content, mimetype='application/json', status=None, content_type='application/json'): | |
json_text = json.dumps(content, cls=DateTimeEncoder) | |
super(JsonResponse, self).__init__( | |
content=json_text, | |
status=status, | |
content_type=content_type) | |
# GET /posts/123/comments/456.json | |
# => {"id": 456, "content": "...", "user_id": 9, "post": {"id": "123", "title": "...", "content": "..."} } | |
def posts_comments_item_json(request, post_id, comment_id): | |
post = get_object_or_404(Post, pk=post_id) | |
comment = post.comment_set.get(pk=comment_id) | |
result = model_to_dict(comment).copy() | |
result.update(dict(post=model_to_dict(post))) | |
return JsonResponse(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
view:
return JsonResponse(result, encoder=DateTimeEncoder)