gpt4 book ai didi

django rest框架列表更新api View

转载 作者:行者123 更新时间:2023-12-05 06:29:46 31 4
gpt4 key购买 nike

我正在尝试向列表项添加更新选项。因此,如果有人对其执行“PATCH”请求,我将获取详细信息并进行更新。这是我的实现代码

class SwitchListView(UpdateModelMixin, ListAPIView):
serializer_class = serializers.SwitchSerializer
lookup_field = 'home_id'

def get_queryset(self):
home_id = self.kwargs.get('home_id', None)
if home_id is None or int(home_id) < 0 or \
self.request.user.pk != models.Home.objects.filter(pk=home_id)[0].user.pk:
return models.Switch.objects.none()
query = models.Switch.objects.filter(home=models.Home.objects.filter(pk=home_id))
return query

def get(self, request, *args, **kwargs):
return super(SwitchListView, self).get(request, *args, **kwargs)

def partial_update(self, request, *args, **kwargs):
print("Came here")
data = request.data['data']
for i in data:
query = self.get_queryset().filter(i['pk'])
if query.exists():
query.switch_status = i['switch_status']
query.save()

return Response({'message': 'successfully updated switch!'})

但这里对 api 的请求只接受 GET、HEAD 和 OPTIONS。我什至尝试添加 http_method_names = ('get', 'patch') 但即使这样也行不通!!

有什么办法可以将补丁请求放到 View 中吗?

谢谢

最佳答案

这是我的实现,FWIW:

from rest_framework import viewsets
from rest_framework.response import Response

class MyListView(viewsets.mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = ...
queryset = MyModel.objects.all()

def list_update(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
instances = list(queryset)
count = len(instances)
# TODO perhaps validate for max allowed count, before doing list(queryset) !
data = [request.data] * count
serializer = self.get_serializer(
instances, data, many=True, partial=True)
serializer.is_valid(raise_exception=True)
self.perform_list_update(serializer)
return Response(status=204)

def perform_list_update(self, serializer):
for instance, data in zip(
serializer.instance, serializer.validated_data):
for attr, value in data.items():
setattr(instance, attr, value)
instance.save()
# alternatively use a queryset.update, but be aware that it will not
# fire pre_save and post_save signals

如果你没有使用 DRF 路由器(因为当做任何像这样的“自定义”时,只使用裸 View 通常更轻松),像这样编辑 urls.py:

urlpatterns = [
...
re_path(
r'^path/to/mymodels',
MyListView.as_view({
'get': 'list',
'patch': 'list_update', # <--
}),
),
]

如果使用路由器,这个小 hack 可以工作并且很简单,但不是非常好:

router = routers.DefaultRouter(trailing_slash=False)
router.routes[0].mapping['patch'] = 'list_update' # <--
...

覆盖 View 集上的 get_serializer_class 以便为 list_update 操作使用不同的序列化程序也可能有意义。

关于django rest框架列表更新api View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236669/

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