2017-07-09 8 views
1

私は2つのモデルをここにタグと質問があります。私が望むのは、質問モデルとManyToMany関係でタグモデルが関連している質問シリアライザの中に明示的にタグモデルを直列化することだけです。DjangoRestFrameworkでManyToManyFieldをシリアライズ

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

TagSerializerクラスをシリアル化しようとしています。データをシリアル化するためにコードを変更してみてください:あなたはオーバーライドto_representation方法である理由

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) 

また、私は取得できませんでした。 だけQuestionSerializertagフィールドを定義してください:

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

私はネストされたデータへの投稿のためにもそれが書き込み可能なようにしたいです。 –

関連する問題