gpt4 book ai didi

python - ModelViewSet - 更新嵌套字段

转载 作者:太空狗 更新时间:2023-10-29 16:56:59 26 4
gpt4 key购买 nike

我目前正在使用 Django Rest Framwork 开发 Django。

我无法更新嵌套对象字段中的对象。


序列化器.py

class OwnerSerializer(serializers.ModelSerializer):
class Meta:
model = Owner
fields = ('id', 'name')

class CarSerializer(serializers.ModelSerializer):
owner = ownerSerializer(many=False, read_only=False)
class Meta:
model = Car
fields = ('id', 'name', 'owner')

view.py

class OwnerViewSet(viewsets.ModelViewSet):
queryset = Owner.objects.all()
serializer_class = OwnerSerializer

class CarViewSet(viewsets.ModelViewSet):
serializer_class = CarSerializer
queryset = Car.objects.all()

def create(self, request):
serialized = self.serializer_class(data=request.DATA)
if serialized.is_valid():
serialized.save()
return Response(status=HTTP_202_ACCEPTED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

当我这样做时:

Request URL:http://localhost:9000/api/v1/cars/1/?format=json
Request Method:PUT
Request Paylod :
{
"id":1,
"name": "TEST",
"ower": {
"id":1,
"name": "owner_test"
}
}

我得到以下响应:

The `.update()` method does not support writable nestedfields by default.
Write an explicit `.update()` method for serializer `app.serializers.CarSerializer`,
or set `read_only=True` on nested serializer fields.

知道:

  • 我想在 GET 上保持所有者序列化;
  • 我们可以想象汽车被另一个物体嵌套等等......

更新汽车时想换车主怎么办

最佳答案

有点晚了,但是,试试这个,

class OwnerSerializer(serializers.ModelSerializer):
class Meta:
model = Owner
fields = ('id', 'name')
extra_kwargs = {
'id': {
'read_only': False,
'required': True
}
} #very important

def create(self, validated_data):
# As before.
...

def update(self, instance, validated_data):
# Update the instance
instance.some_field = validated_data['some_field']
instance.save()

# Delete any detail not included in the request
owner_ids = [item['owner_id'] for item in validated_data['owners']]
for owner in cars.owners.all():
if owner.id not in owner_ids:
owner.delete()

# Create or update owner
for owner in validated_data['owners']:
ownerObj = Owner.objects.get(pk=item['id'])
if ownerObje:
ownerObj.some_field=item['some_field']
....fields...
else:
ownerObj = Owner.create(car=instance,**owner)
ownerObj.save()

return instance

关于python - ModelViewSet - 更新嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27825049/

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