1个模型的django-rest-framework多个序列化器?
Posted
技术标签:
【中文标题】1个模型的django-rest-framework多个序列化器?【英文标题】:django-rest-framework multiple serializer for 1 model? 【发布时间】:2014-11-12 07:50:02 【问题描述】:假设你想放弃
field1, field2, field3
详细请求。field1, field2
列表请求。field1
其他更简单的列表请求。
我已经看到使用 get_serializer_class
和 self.action 的示例,它可以处理细节与列表的情况。 (https://***.com/a/22755648/433570)
我应该定义两个视图集和两个 url 端点吗? 还是这里有更好的方法?
我想这也可以应用于美味派。 (两个资源?)
【问题讨论】:
Django Rest Framework: Dynamically return subset of fields的可能重复 【参考方案1】:我自己没有测试过,但我认为你可以覆盖你需要的方法。
根据the documentation(标记路由的额外操作),您可以这样做:
class UserViewSet(viewsets.ViewSet):
"""
Example empty viewset demonstrating the standard
actions that will be handled by a router class.
If you're using format suffixes, make sure to also include
the `format=None` keyword argument for each action.
"""
def list(self, request):
pass
def create(self, request):
pass
def retrieve(self, request, pk=None):
pass
def update(self, request, pk=None):
pass
def partial_update(self, request, pk=None):
pass
def destroy(self, request, pk=None):
pass
或者如果您需要自定义方法:
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
@detail_route(methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.DATA)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.save()
return Response('status': 'password set')
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@list_route()
def recent_users(self, request):
recent_users = User.objects.all().order('-last_login')
page = self.paginate_queryset(recent_users)
serializer = self.get_pagination_serializer(page)
return Response(serializer.data)
【讨论】:
ok,用@list_route,可以添加多个列表端点,用代码***.com/questions/22616973/…,我可以达到想要的效果。以上是关于1个模型的django-rest-framework多个序列化器?的主要内容,如果未能解决你的问题,请参考以下文章
为啥 django-rest-framework 不显示 OneToOneField 数据 - django