【问题标题】:Serializing ManyToManyField in DjangoRestFramework在 DjangoRestFramework 中序列化 ManyToManyField
【发布时间】:2017-07-09 09:37:05
【问题描述】:

我在这里有 2 个模型标签和问题。我想要的只是序列化标签模型,而无需在问题序列化器中显式地序列化标签模型,其中标签模型与问题模型的多对多关系相关。

class Question(models.Model):
    question = models.TextField(blank=False, null=False)
    question_image = models.ImageField(blank=True, null=True, upload_to='question')
    opt_first = models.CharField(max_length=50, blank=False, null=False)
    opt_second = models.CharField(max_length=50, blank=False, null=False)
    opt_third = models.CharField(max_length=50, blank=False, null=False)
    opt_forth = models.CharField(max_length=50, blank=False, null=False)
    answer = models.CharField(max_length=1, choices=(('1','1'),('2','2'),('3','3'),('4','4')))
    description = models.TextField(blank=True,null=True )
    tag = models.ManyToManyField(Tag)
    created_on  = models.DateTimeField(default= timezone.now)

class Tag(models.Model):
    name = models.CharField(max_length = 50, null=False, unique=True)

我有这两个模型的序列化器类

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('name',)

class QuestionSerializer(serializers.ModelSerializer):
     # tag = TagSerializer(many=True)
    def to_representation(self, obj):
        rep = super(QuestionSerializer, self).to_representation(obj)
        rep['tag'] = []
        for i in obj.tag.all():
           # rep['tag'].append({'id':i.id,'name':i.name})
           # Below doesn't give JSON representation produces an error instead
           rep['tag'].append(TagSerializer(i)) 
        return rep

    class Meta:
        model = Question
        fields = ('question', 'question_image', 'opt_first', 'opt_second', 'opt_third', 'opt_forth', 'answer', 'description', 'tag')
        read_only_fields = ('created_on',)

这里在 QuestionSerializer 的 to_repesentation 方法中使用 TagSerializer 不会序列化标记对象。而是产生错误
ExceptionValue : TagSerializer(<Tag: Geography>): name = CharField(max_length=50, validators=[<UniqueValidator(queryset=Tag.objects.all())>]) is not JSON serializable

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您正在尝试序列化 TagSerializer 类。尝试更改代码以序列化数据:

    for i in obj.tag.all():
           # rep['tag'].append({'id':i.id,'name':i.name})
           # Below doesn't give JSON representation produces an error instead
           ser = TagSerializer(i)
           rep['tag'].append(ser.data) 
    

    我也不明白你为什么要覆盖to_representation 方法。 尝试在QuestionSerializer 中定义tag 字段:

    tag = TagSerializer(read_only=True, many=True)
    

    【讨论】:

    • 我想让它也可写以用于嵌套数据发布。
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2015-08-23
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多