【问题标题】:How to serialize a list of model instances?如何序列化模型实例列表?
【发布时间】:2020-04-05 11:17:36
【问题描述】:

我有一个词素列表。我需要序列化它(比如here):

lexemes = [Lexeme('a', 'b', 'c'), Lexeme('d', 'e', 'f')]
serializer = LexemeSerializer(data=lexemes, many=True)
if serializer.is_valid():
    return Response(serializer.validated_data)
else:
    return Response(
        serializer.errors,
        status=status.HTTP_400_BAD_REQUEST
    )

我的回答是

[{"non_field_errors": ["无效数据。需要字典,但得到了 Lexeme。"]},{"non_field_errors": ["无效数据。需要字典,但得到 Lexeme。"]}]

class Lexeme(models.Model):
    lemma = models.CharField(max_length=30)
    part_of_speech = models.CharField(max_length=30)
    endings = models.CharField(max_length=30)

class LexemeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Lexeme
        fields = '__all__'

我的代码与引用问题的代码之间的区别我正在使用模型序列化程序。是错误的原因吗?我该如何解决?

【问题讨论】:

    标签: django-rest-framework django-serializer


    【解决方案1】:

    我不确定ModelSerializer 是否接受带有many=True 选项的实例列表。

    作为serializer = LexemeSerializer(data=lexemes, many=True)data 参数,您需要传递queryset

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2013-07-10
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      相关资源
      最近更新 更多