如何在Django Rest Framework的manytomanyfield中的序列化器中获取密钥的值?

时间:2019-03-09 02:41:45

标签: python django django-rest-framework

我在序列化期间显示数据时遇到问题。

这是我的模特

from django.db import models

class Paradigmn(models.Model):
    name = models.CharField(max_length=50)

def __str__(self):
    return self.name

class Language(models.Model):
    name = models.CharField(max_length=50)
    paradigm = models.ForeignKey(Paradigmn, on_delete=models.CASCADE)

def __str__(self):
    return self.name

class Programmer(models.Model):
    name = models.CharField(max_length=50)
    languages = models.ManyToManyField(Language, related_name='languages')

def __str__(self):
    return self.name

这是我的序列化器:

from languages.models import Language, Paradigmn, Programmer

class LanguageSerializer(serializers.ModelSerializer):
    paradigms = serializers.ReadOnlyField(source='paradigm.name')

    class Meta:
        model = Language
        fields = ('id', 'name', 'paradigms')

class ParadigmnSerializer(serializers.ModelSerializer):

    class Meta:
        model = Paradigmn
        fields = ('id', 'name',)    

class ProgrammerSerializer(serializers.ModelSerializer):
    languages = LanguageSerializer(many=True, read_only=True)

    class Meta:
        model = Programmer
        fields = ('id', 'name', 'languages') 

这是结果:

[
 {
    "id": 1,
    "name": "Ryan",
    "languages": [
        {
            "id": 1,
            "name": "Java",
            "paradigms": "Object-Oriented"
        }
    ]
},
{
    "id": 2,
    "name": "Jean",
    "languages": [
        {
            "id": 3,
            "name": "Python",
            "paradigms": "Object-Oriented"
        }
    ]
},
{
    "id": 3,
    "name": "Michael",
    "languages": [
        {
            "id": 2,
            "name": "Elixir",
            "paradigms": "Functional"
        }
    ]
}

我只想在语言数组上显示语言名称,而不是语言数组的所有详细信息。最好的解决方案是什么?

1 个答案:

答案 0 :(得分:0)

一种解决方案:

from rest_framework.serializers import SerializerMethodField

class ProgrammerSerializer(serializers.ModelSerializer):
    languagelist = SerializerMethodField()

    def get_languagelist(self, obj):
        return [{'name': i.name} for i in obj.languages.all()]

    class Meta:
        model = Programmer
        fields = ('id', 'name', 'languagelist')