我尝试使用嵌套表示创建和更新资源。
我看了一眼 - > http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations。但我不知道在何处进行验证以验证我的嵌套资源(由其id定义)是否存在。
{
"name": "this is my name"
"network": {
"code": "existing_code",
"operator": "existing_op"
},
}
def create(self, validated_data):
network = validated_data.pop("network")
#this could throw a DoesNotExist exception !!!!
validated_data["network"] = Network.objects.get(operator=network["operator"], code=network["code"])
instance = manny.common.models.DeliveryPoint.objects.create(**validated_data)
return instance
可以直接在ModelSerializer上的验证器中检查:
def validate(self, data):
#some code here....
if not Network.objects.filter(operator=data["operator"], code=data["code"]).exists():
raise serializers.ValidationError("network doesn't exist")
return data
或者我是否必须重写ModelViewSet的create方法?
感谢您的帮助!