[英]django-rest-framework multiple serializer for 1 model?
Suppose you want to give out 假设你想要放弃
{field1, field2, field3}
on detail request. 详细请求中的
{field1, field2, field3}
。
{field1, field2}
on list request. 列表请求中的
{field1, field2}
。
{field1}
on some other simpler list request. {field1}
关于其他一些更简单的列表请求。
I have seen examples using get_serializer_class
with self.action which can handle detail vs list scenario. 我已经看到了使用实例
get_serializer_class
与self.action它可以处理细节VS列表场景。 ( https://stackoverflow.com/a/22755648/433570 ) ( https://stackoverflow.com/a/22755648/433570 )
Should I define two viewsets and two url endpoints? 我应该定义两个视图集和两个url端点吗?
Or is there a better approach here? 或者这里有更好的方法吗?
I guess this could be applied to tastypie as well. 我想这也适用于tastypie。 (two resources?)
(两个资源?)
I haven't tested it myself but I think you can do it overriding the methods you need. 我自己没有测试过,但我认为你可以覆盖你需要的方法。
According to the documentation (Marking extra actions for routing) you could do: 根据文档 (标记路由的额外操作),您可以:
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
Or if you need custom methods: 或者如果您需要自定义方法:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.