简体   繁体   中英

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

I have serialised a model into JSON that has foreign keys. The API will show the title of the foreign key but will not nest the data that belongs to that foreign key. How do I do this.

serializers.py

class ReportFieldSerializers(serializers.ModelSerializer):
    form = serializers.RelatedField()
    class Meta:
        model = ReportField
        fields = (
            'id',
            'title',
            'form'
        )

api.py

class ReportFieldList(APIView):
    def get(self, request, format=None):
        report_field = ReportField.objects.all()
        serialized_report_field = ReportFieldSerializers(report_field, many=True)
        return Response(serialized_report_field.data)

class ReportFieldDetail(APIView):
    def get_object(self, pk):
        try:
            return ReportField.objects.get(pk=pk)
        except ReportField.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        report_field = self.get_object(pk)
        serialized_report_field = ReportFieldSerializers(report_field)
        return Response(serialized_report_field.data)

models.py

class Report(models.Model):
    title = models.CharField()
    form = models.ForeignKey()

class Form(models.Model):
    # Form details

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM