gpt4 book ai didi

1 个模型的 django-rest-framework 多个序列化程序?

转载 作者:行者123 更新时间:2023-12-04 21:15:03 26 4
gpt4 key购买 nike

假设你想放弃
{field1, field2, field3}根据详细要求。{field1, field2}在列表请求中。{field1}在其他一些更简单的列表请求上。

我见过使用 get_serializer_class 的例子使用 self.action 可以处理细节与列表场景。 ( https://stackoverflow.com/a/22755648/433570 )

我应该定义两个 View 集和两个 url 端点吗?
或者这里有更好的方法吗?

我想这也适用于 Tastypie 。 (两个资源?)

最佳答案

我自己还没有测试过,但我认为你可以覆盖你需要的方法。

根据 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)

关于1 个模型的 django-rest-framework 多个序列化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25904744/

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