Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 768
Chris Meek Avatar asked Oct 24 '25 19:10

Chris Meek


1 Answers

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

like image 66
cezar Avatar answered Oct 26 '25 07:10

cezar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!