Django REST Framework新手求助:如何创建无模型的JSON视图?
嘿,作为DRF新手碰到这种情况太正常啦!其实不用绑定数据库模型也能轻松生成JSON视图,我来一步步给你捋清楚~
首先先把你没写完的Comment类补全,确保它的属性和Serializer字段对应上:
from django.utils import timezone class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content # 如果没传created时间,就用当前时间 self.created = created or timezone.now()
你的CommentSerializer写得没问题,它本来就支持序列化普通Python对象,不止是Model实例:
from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField()
接下来就是写视图了,有两种常用方式:
方式一:基于APIView的类视图
这种方式更符合DRF的类视图风格,扩展性更强:
from rest_framework.views import APIView from rest_framework.response import Response class CommentView(APIView): def get(self, request): # 创建一个Comment实例 test_comment = Comment(email="user@example.com", content="这是一条测试评论") # 序列化这个对象 serializer = CommentSerializer(test_comment) # 返回JSON响应 return Response(serializer.data)
方式二:函数视图(更轻量化)
如果你的逻辑很简单,用函数视图更快捷:
from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) # 指定允许的请求方法 def comment_view(request): test_comment = Comment(email="user@example.com", content="这是一条测试评论") serializer = CommentSerializer(test_comment) return Response(serializer.data)
序列化多个对象
如果要返回多条评论的JSON数组,只需要给Serializer加上many=True参数:
# 比如在视图里创建多个Comment实例 comments_list = [ Comment(email="user1@example.com", content="第一条测试评论"), Comment(email="user2@example.com", content="第二条测试评论") ] # 序列化时加上many=True serializer = CommentSerializer(comments_list, many=True) return Response(serializer.data)
最后别忘了配置路由,在你的urls.py里添加:
from django.urls import path from .views import CommentView, comment_view urlpatterns = [ # 类视图路由 path('comment/', CommentView.as_view(), name='comment-detail'), # 函数视图路由 path('comment-func/', comment_view, name='comment-func-detail'), ]
核心逻辑就是:DRF的Serializer不仅能处理Model实例,只要你的Python对象有和Serializer字段同名的属性,就能被正常序列化~
内容的提问来源于stack exchange,提问作者jax
相关产品推荐
相关产品推荐

