whatf
whatf

Reputation: 6468

django rest framework nested relationship view

Following is my model representation

class A(models.Model)
    ....__annotations__
    name_a = models.CharField(max_length=100)

 class B(models.Model):
     a = models.ForeignKey(A)
     name_b = models.CharField(max_length=100)
     ....__annotations__

class C(models.Model):
    b = models.ForeignKey(B)

Following is the serializer for model C

class CSerializer(serializers.ModelSerializer):
    
    class Meta:

        model = C
        fields = '__all__'

In the serializer I would like to display the name of A and B. How to achieve the same? Currently the serialized data shows the id - pkey.

Upvotes: 1

Views: 49

Answers (1)

Kyell
Kyell

Reputation: 636

You have to create a serializer for each model then use it for the next one

class ASerializer(serializers.ModelSerializer):
    class Meta:
        model = A
        fields = '__all__'

class BSerializer(serializers.ModelSerializer):
    a = ASerializer()

    class Meta:
        model = B
        fields = '__all__'

class CSerializer(serializers.ModelSerializer):
    b = BSerializer()

    class Meta:
        model = C
        fields = '__all__'

Another way is to use the source parameter in specifying field

class CSerializer(serializers.ModelSerializer):
    # field_a and field_b are arbitrary names, any valid variable name would work.
    field_a = serializers.CharField(source="b__a__name_a", read_only=True)
    field_b = serializers.CharField(source="b__name_b", read_only=True)
    
    class Meta:
        model = C
        fields = [
            # Other fields here,
            "field_a",
            "field_b",
        ]

P.S. I don't know how it will behave when doing a create/update action in the serializer.

Upvotes: 2

Related Questions