[英]Django rest framework: Insert multiple objects in one post request
[英]Django Rest Framework, updating multiple objects in one
我正在嘗試使用PATCH
將多個對象更新到我的 Django 后端。 這是我發送的請求:
[
{
"pk":78,
"weekday":1,
"from_hour":"21:00",
"to_hour":"12:00:00",
"closed":false,
"lunch":true,
"lunch_start":null,
"lunch_end":null,
"lunch2":false,
"lunch_start2":null,
"lunch_end2":null,
"appointment_interval":15,
"num_appointments_interval":4,
"office":79
},
{
"pk":79,
"weekday":2,
"from_hour":"09:00:00",
"to_hour":"12:00:00",
"closed":false,
"lunch":true,
"lunch_start":null,
"lunch_end":null,
"lunch2":false,
"lunch_start2":null,
"lunch_end2":null,
"appointment_interval":15,
"num_appointments_interval":4,
"office":79
},
{
"pk":80,
"weekday":3,
"from_hour":"09:00:00",
"to_hour":"12:00:00",
"closed":false,
"lunch":true,
"lunch_start":null,
"lunch_end":null,
"lunch2":false,
"lunch_start2":null,
"lunch_end2":null,
"appointment_interval":15,
"num_appointments_interval":4,
"office":79
},
{
"pk":81,
"weekday":4,
"from_hour":"09:00:00",
"to_hour":"12:00:00",
"closed":false,
"lunch":false,
"lunch_start":"14:59:50",
"lunch_end":"14:59:51",
"lunch2":false,
"lunch_start2":null,
"lunch_end2":null,
"appointment_interval":15,
"num_appointments_interval":4,
"office":79
},
]
我將其發送到我試圖序列化和更新數據的自定義視圖。
@api_view(['PATCH'])
@parser_classes((JSONParser,))
def updateOfficeHours(request):
office_id = request.data[0]['office']
qs = OfficeHour.objects.filter(office__pk=office_id)
office_hours = OfficeHoursSerializer(qs, data=request.data, many=True, partial=True)
if not office_hours.is_valid():
print(":(")
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
office_hours.save()
return Response(status=status.HTTP_200_OK)
我最終只得到這個錯誤:
AttributeError: 'QuerySet' object has no attribute 'pk'
當您正在尋找一個 object 時,似乎會出現此錯誤,但我有many=True
。 我究竟做錯了什么?
ListSerializer可以解決這個問題。 就是這樣:
class OfficeHoursListSerializer(serializers.ListSerializer):
def update(self, instances, validated_data):
# here you can implement your own logic for updating objects
# this is just an example
result = []
for instance in instances:
for data in validated_data:
if data['id'] == instance.pk:
instance.some_field = data['some_field']
instance.save()
result.append(instance)
return result
然后您需要在 OfficeHoursSerializer 中指定OfficeHoursSerializer
:
class OfficeHoursSerializer(serializers.ModelSerializer):
# It needs to identify elements in the list using their primary key,
# so use a writable field here, rather than the default which would be read-only.
id = serializers.IntegerField()
...
class Meta:
...
list_serializer_class = OfficeHoursListSerializer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.