[Django]-Django Rest Framework: how do I Display content of Foreign keys in JSON

6👍

There is an option depth, that can be used in the Meta class of the serializer. For example:

class ReportFieldSerializers(serializers.ModelSerializer):

    class Meta:
        model = ReportField
        fields = (
            'id',
            'title',
            'form'
        )
        depth = 1

This will go one step down in the related models. As you see you don’t need the RelatedField. If, let’s say, there would be a third model class, for example:

class Form(models.Model):
    example = ForeignKey('AnotherModel')

class AnotherModel(models.Model):
    # model fields

you could also use depth=2 in your ReportFieldSerializer to display the information for this model.

I assume that in your model Report the field form shows to Form: models.ForeignKey(Form).

I answered already a similar question here:
Django rest_framework serializer with inner relationship

👤cezar

Leave a comment