简体   繁体   English

Django Rest Framework:如何在JSON中显示外键的内容

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

I have serialised a model into JSON that has foreign keys. 我已经将模型序列化为具有外键的JSON。 The API will show the title of the foreign key but will not nest the data that belongs to that foreign key. API将显示外键的标题,但不会嵌套属于该外键的数据。 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 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

There is an option depth , that can be used in the Meta class of the serializer. 有一个可选的depth ,可以在序列化器的Meta类中使用。 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 . 如您所见,您不需要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. 您还可以在ReportFieldSerializer使用depth=2来显示此模型的信息。

I assume that in your model Report the field form shows to Form : models.ForeignKey(Form) . 我假设在您的模型Report ,字段form显示为Formmodels.ForeignKey(Form)

I answered already a similar question here: Django rest_framework serializer with inner relationship 我已经在这里回答了类似的问题: 具有内部关系的Django rest_framework序列化程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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