0

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?

1

Write your serializer as ,

#serializers.py
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,

#views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response


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

References

  1. DRF-Serializer
  2. DRF-views

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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