gpt4 book ai didi

Django Rest-framework 创建没有模型的 View

转载 作者:行者123 更新时间:2023-12-02 05:43:49 25 4
gpt4 key购买 nike

我对 Django Rest-framework 很陌生,并尝试渲染一个不基于模型的简单 JSON View 。我不知道如何做到这一点,因为所有示例都涉及从模型类渲染 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

最佳答案

您可以像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'),
]

关于Django Rest-framework 创建没有模型的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com