[Answer]-Nested Relationship in django rest framework

1👍

Forgive me if this is off track but it looks to me like the model doesn’t know anything about the nested field (vdi). Did you try popping it off validated_data?

Here’s a small (untested) example of what I have been working on using djangorestframework==3.1.3 with Django==1.7.

models.py:

class Child(models.Model):
    child_data = models.CharField(max_length=255)

class Parent(models.Model):
    # Set 'related_name' to the nested field name in the serializer.
    child_id = models.ForeignKey(Child, related_name='child')

serializers.py:

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Child

class ParentSerializer(serializers.ModelSerializer):
    # The ForeignKey in the model is supplied with this name so that GET
    # requests can populate this and the source field below makes it
    # accessible in create after validation.
    child = TestInfoSerializer(source='child_id')

    class Meta:
        model = Parent
    fields = ('child', )

    def create(self, validated_data):
        child_data = validated_data.pop('child_id')  # strip out child_id for subsequent Parent create
        try:
            # try to find an existing row to fulfill the foreign key
            child_instance = Child.objects.filter(**child_data)[0]
        except IndexError:
            # create a new row
            child_instance = Child.objects.create(**child_data)
        return Parent.objects.create(child_id=child_instance, **validated_data)

With this I can POST nested JSON without thinking about the foreign key:

{
    "child": {
        "child_data": "asdf"
    }
}

GET also returns the nested representation with this setup.

I hope this helps.

Leave a comment