我是Django rest-framework的新手,并试图渲染一个不基于模型的简单JSON视图。我无法弄清楚如何执行此操作,因为所有示例都涉及从Model类渲染JSON。以下是我想要做的简单示例。
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
class Comment(object):
def __init__(self, email, content, created=None):
self.email = email
self.content = content
self.created = created or datetime.now()
def comment_view(request):
comment = Comment(email='leila@example.com', content='foo bar')
serializer = CommentSerializer(comment)
json = JSONRenderer().render(serializer.data)
return json
答案 0 :(得分:1)
您可以像here一样使用它:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def comment_view(request):
comment = Comment(email='leila@example.com', content='foo bar')
serializer = CommentSerializer(comment)
return Response(serializer.data)
最后别忘了把它放在urls.py
:
urlpatterns = [
path('comments/', comment_view, name='comment-view'),
]