django rest framework 3.1 Handle create/update in ModelSerializer where do i validate the nested data? -


i try create , update resources using nested representation.

i took here -> http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations. don't know put validation verify nested resources, not defined id, exists.

json

{     "name": "this name"     "network": {         "code": "existing_code",         "operator": "existing_op"     },  } 

create method of serializer

def create(self, validated_data):      network = validated_data.pop("network")      #this throw 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 

is okay check in validator directly on modelserializer:

validate method of serializer

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 

or have rewrite create method of modelviewset ?

thanks !

why don't use get_object_or_404 (https://docs.djangoproject.com/fr/1.8/topics/http/shortcuts/#get-object-or-404) instead of network.objects.get ?

if network object doesn't exist, raised exception make 404 error, , won't need handle manually.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -