1

I have two simple serializers:

class ZoneSerializer(serializers.ModelSerializer):
    class Meta:
        model = Zone
        fields = ('id', 'name')

class CitySerializer(serializers.ModelSerializer):
    zone = ZoneSerializer(source='zone')

    class Meta:
        model = City
        fields = ('id', 'name', 'zone')

So client-side receives JSON objects like:

{
    "id": 11, 
    "name": "City1", 
    "zone": {
        "id": 2, 
        "name": "Zone 2"
    }
}

Now, when I receive JSON from client-side as...

{
    "name": "NewCity",
    "zone": {
        "id": 2,
        "name": "Zone 2"
    }
}

... and want to POST (create) it as a new "city", I want my ModelSerializer to know that "zone" in JSON is a foreign key to Zone model, and it shouldn't be inserted to db as a new "zone".

Is there a way to achieve that? Or must I use RelatedField instead, although I want to pass and receive full detailed zone rather than just primary keys?

1 Answer 1

1

According to this answer by the author of django-rest-framework, the answer is no, it is not possible ("nested serializers do not currently support write operations") as of January 2013.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.