ErrorDetail(string='应为项目列表,但得到类型为“ReturnDict.”,代码='not'u a'u list')

2024-06-01 08:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

当我测试ThankYouMessage时,我得到错误{'images': {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "ReturnDict".', code='not_a_list')]}}

测验

class ThankYouMessagesSerializerTestCase(MediaTestCase, TestCase):
    def setUp(self) -> None:
        self.thank_you_message = ThankYouMessageFactory()
        self.thank_you_image = ThankYouImageFactory()

    def test_thank_you_message_deserialize(self) -> None:
        image_data = ThankYouMessageImageSerializer(self.thank_you_image).data
        thank_you_data = ({'text': 'Some text', 'images': image_data})
        serializer = ThankYouMessagesSerializer(data=thank_you_data)
        serializer.is_valid()
        print(serializer.errors)
        # {'images': {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "ReturnDict".', code='not_a_list')]}}
        self.assertTrue(serializer.is_valid())

模型

class ThankYouMessage(models.Model):
    donation = models.ForeignKey("donation.Donation", on_delete=models.CASCADE, related_name='thank_message', unique=True)
    text = models.TextField()


class ThankImage(models.Model):
    message = models.ForeignKey("donation.ThankYouMessage", on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to="thankmessageimages/")

工厂

class ThankYouMessageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ThankYouMessage

    donation = factory.SubFactory(DonationFactory)
    text = factory.Sequence(lambda n: f"Thank you {n}")
When I test При тестировании сериализатора получаю ошибку

class ThankYouImageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ThankImage

    image = factory.django.ImageField(name=f"testimage.jpeg", color="blue")
    message = factory.SubFactory(ThankYouMessageFactory)

序列化程序

class ThankYouMessageImageSerializer(ModelSerializer):
    class Meta:
        model = ThankImage
        fields = '__all__'
        read_only_fields = ("message", "id")


class ThankYouMessagesSerializer(ModelSerializer):
    images = ThankYouMessageImageSerializer(many=True)
    donation = serializers.CharField(source='donation.id', read_only=True)
    donor_id = serializers.CharField(source='donation.donor.id', read_only=True)

    class Meta:
        model = ThankYouMessage
        fields = 'text', 'donation', 'donor_id', 'images'

如果我写image_data = ThankYouMessageImageSerializer(self.thank_you_image, many=True).data,我得到TypeError: 'ThankImage' object is not iterable


Tags: textimageselfyouidtruemessagedata
1条回答
网友
1楼 · 发布于 2024-06-01 08:16:37

你的ThankYouMessage将有一个相关字段images,它充当ThankYouImage的集合,因此你需要你的thank_you_image作为列表。您可以使用.build_batch()工厂方法构建它,并使用many=True参数序列化它

class ThankYouMessagesSerializerTestCase(MediaTestCase, TestCase):
    def setUp(self) -> None:
        ...
        self.thank_you_images = ThankYouImageFactory.build_batch(3)

    def test_thank_you_message_deserialize(self) -> None:
        image_data = ThankYouMessageImageSerializer(self.thank_you_images, many=True).data
        ...

当我测试它时,您的image_data仍然无法序列化并显示此错误:

The submitted data was not a file. Check the encoding type on the form.

但我认为这是另一个话题


顺便说一句,为什么不直接序列化生成的self.thank_you_message而不是thank_you_data?你想在这里测试什么

相关问题 更多 >