在DjangoRestFramework中序列化ManyToManyField

时间:2017-07-09 09:37:05

标签: django django-rest-framework

我这里有2个模型标签和问题。我想要的是序列化标签模型,而不是显式地在问题序列化器内部,其中Tag模型与ManyToMany与问题模型的关系相关。

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

1 个答案:

答案 0 :(得分: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方法。 尝试在tag中定义QuestionSerializer字段:

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