I want to serialize the data

class Main(models.Model):
    title = models.CharField()

class ForeignKey(models.Model):
    main = models.ForeignKey(Main,on_related='foreign_key')

I want to get the result like

{'title':'hello', 'foreign_key':'['foreign_key1','foreign_key2','foreign_key3']'

I first thought I could make it work in the 'views.py', but some documents told me that there is a thing like 'listField' in serializer, which has too little examples..

What would be the way here?


Write your serializer as ,

from rest_framework import serializers

class ForeignKeySerializer(serializers.ModelSerializer):
    class Meta:
        model = ForeignKey
        fields ='__all__'

class MainSerializer(serializers.ModelSerializer):
    foreign_key = ForeignKeySerializer(source='foreignkey_set', many=True)

    class Meta:
        model = Main
        fields = ("title", "foreign_key")

then write your views as,

from rest_framework.decorators import api_view
from rest_framework.response import Response

def sample_view(request):
    queryset = Main.objects.all()
    serializer = MainSerializer(queryset, many=True)
    return Response(data=serializer.data)


  1. DRF-Serializer
  2. DRF-views

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.