本文介绍了Django Rest Framework:如何在JSON中显示外键的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将一个模型序列化为具有外键的JSON。 API将显示外键的标题,但不会嵌套属于该外键的数据。我该怎么做。

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

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

models.py

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

class Form(models.Model):
    # Form details


推荐答案

有一个选项 depth 可以使用在序列化器的Meta类中。例如:

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

这将在相关模型中往下移一步。如您所见,您不需要 RelatedField 。假设有第三个模型类,例如:

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

您还可以在 ReportFieldSerializer 中使用 depth = 2 该模型的信息。

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

我假设在您的模型报告中,字段 显示为表格 models.ForeignKey(Form)

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

这篇关于Django Rest Framework:如何在JSON中显示外键的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 10:55