Reputation: 1375
I have 2 models here Tag and Question. All i want is to serialize the Tag Model without explicitly inside the Question Serializer where Tag model is related by ManyToMany relation with Question model.
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)
And I have serializers classes for these two models
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',)
Here on using TagSerializer in the to_repesentation method of QuestionSerializer doesn't serialize the tag object. Instead produces error
ExceptionValue : TagSerializer(<Tag: Geography>):
name = CharField(max_length=50, validators=[<UniqueValidator(queryset=Tag.objects.all())>]) is not JSON serializable
Upvotes: 1
Views: 255
Reputation: 47354
You are trying to serialize TagSerializer
class. Try to change code to serialize data:
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)
Also I didn't get why you are override to_representation
method.
Try just to define tag
field in QuestionSerializer
:
tag = TagSerializer(read_only=True, many=True)
Upvotes: 1