我已经将一个模型序列化为具有外键的JSON。API将显示外键的标题,但不会嵌套属于该外键的数据。我该怎么做。
序列化程序.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)
模型.py
class Report(models.Model):
title = models.CharField()
form = models.ForeignKey()
class Form(models.Model):
# Form details
最佳答案
有一个选项depth
,可以在序列化程序的元类中使用。例如:
class ReportFieldSerializers(serializers.ModelSerializer):
class Meta:
model = ReportField
fields = (
'id',
'title',
'form'
)
depth = 1
这将在相关模型中降低一步。如您所见,您不需要
RelatedField
。假设有第三个模型类,例如:class Form(models.Model):
example = ForeignKey('AnotherModel')
class AnotherModel(models.Model):
# model fields
您也可以在
depth=2
中使用ReportFieldSerializer
来显示此模型的信息。我假设在您的模型中,
Report
字段显示为form
:Form
。我在这里已经回答了一个类似的问题:
Django rest_framework serializer with inner relationship