Django rest framework serializing many to many field

前端 未结 7 1372
旧时难觅i
旧时难觅i 2020-11-28 03:46

How do I serialize a many-to-many field into list of something, and return them through rest framework? In my example below, I try to return the post together with a list of

相关标签:
7条回答
  • 2020-11-28 04:31

    Django 2.0

    For many to many field, if you want specific one:

    class QuestionSerializer(serializers.ModelSerializer):
    
        topics_list = serializers.SerializerMethodField()
    
        def get_topics_list(self, instance):
            names = []
            a = instance.topics.get_queryset()
            for i in a:
                names.append(i.desc)
            return names
        class Meta:
            model = Question
            fields = ('topics_list',)
    
    0 讨论(0)
提交回复
热议问题