“ GenericRelatedObjectManager”不可JSON序列化

时间:2019-02-11 22:01:13

标签: django django-models django-rest-framework

我已经讨论了多个问题相同的主题,但找不到适合我的解决方案。

我有2个模型,这是2种不同类型的问题:

class Question(models.Model):
    description = models.CharField(max_length=400)
    answers_list = GenericRelation(Answer)

class SuperQuestion(models.Model):
    top_description = models.CharField(max_length=200)
    mid_description = models.CharField(max_length=200)
    meta_description = models.CharField(max_length=1000)
    answers_list = GenericRelation(Answer)

我有一个Answer模型,其中可以包含问题和超级问题的答案:

class Answer(models.Model):
limit = models.Q(app_label='core', model='question') |\
        models.Q(app_label='core', model='superquestion')

content_type = models.ForeignKey(
    ContentType,
    limit_choices_to=limit,
    on_delete=models.CASCADE
)

object_id = models.PositiveIntegerField()
question = GenericForeignKey('content_type', 'object_id')
answer = models.CharField(max_length=500)
additional = models.CharField(
    max_length=2000,
    blank=True,
    null=True,
    default=None
)

我的序列化器:

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = [
            'id',
            'question',
            'answer',
            'created_at'
        ]

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = [
            'id',
            'description',
            'answers_list'
        ]
        depth = 1

class SuperQuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SuperQuestion
        fields = [
            'id',
            'top_description',
            'mid_description',
            'meta_description',
            'answers_list',
        ]
        depth = 1

我想做的是获取所有问题,每个问题都必须包含该问题的所有答案。看起来像这样:

questions = QuestionSerializer(
        QuestionSession.objects.get(
            pk=session_id).questions.all(),
        many=True
    )

但这一切都给了我

  

TypeError:“ GenericRelatedObjectManager”类型的对象不可JSON序列化

我尝试使用第三方rest-framework-generic-relations,但这并没有帮助我。这里怎么了?

1 个答案:

答案 0 :(得分:1)

默认情况下它无法序列化Answers_list,因此您必须将其定义为嵌套的序列化器。

class SuperQuestionSerializer(serializers.ModelSerializer):
    answers_list = AnswerSerializer(many=True)
    class Meta:
        model = SuperQuestion
        fields = [
            'id',
            'top_description',
            'mid_description',
            'meta_description',
            'answers_list',
        ]

与问题相同