我正在尝试使用外键在模型上进行Patch / Put请求。 我覆盖了create和update方法以更新实例:
class CowManagementSerializer(serializers.ModelSerializer):
group = serializers.CharField(required=True, allow_null=False)
class Meta:
model = Cow
fields = ['management_id', 'eid_number', 'group']
def validate(self, attrs):
return attrs
def create(self, validated_data):
try:
group_id = validated_data['group']
eid_number = validated_data['eid_number']
management_id = validated_data['management_id']
print(group_id)
group = Group.objects.get(group_id=group_id, farm__user=self.context['request'].user)
Cow.objects.create(group=group, eid_number=eid_number, management_id=management_id)
return validated_data
except Group.DoesNotExist:
raise serializers.ValidationError("Group with this name does not exist!")
def update(self, instance, validated_data):
group_id = validated_data.pop('group')
group = Group.objects.get(group_id=group_id, farm__user=self.context['request'].user)
instance.group = group
instance.management_id = validated_data['management_id']
instance.eid_number = validated_data['eid_number']
instance.save()
return instance
制作补丁或发出请求只会创建另一个具有相同数据的对象。
发送相同的请求将返回:
{
"eid_number": [
"cow with this eid number already exists."
]
}
之所以有意义,是因为创建了一个新对象。