[Django]-Django Rest Framework – How to get field of foreign key of a foreign key

4👍

Not sure if I understand your example, but it seems you wish to walk the relation from C -> B -> A and get that value. You can follow the relation in the source argument using dot syntax, much like you would if you were accessing the object directly.

class ModelCSerializer(serializers.ModelSerializer):
    field_b = serializers.SlugRelatedField(
        read_only=True,
        source='b.some_field_b',
        slug_field='some_field_b')

    field_a = serializers.SlugRelatedField(
        read_only=True,
        source='b.a.some_field_a',
        slug_field='some_field_a')

    class Meta:
        model = ModelC
        fields = ('some_field_c', 'field_b', 'field_a')

Leave a comment