【问题标题】:ErrorDetail(string='Expected a list of items but got type "ReturnDict".', code='not_a_list')ErrorDetail(string='期望的项目列表,但得到类型“ReturnDict”。', code='not_a_list')
【发布时间】:2020-01-29 12:05:00
【问题描述】:

当我测试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

【问题讨论】:

    标签: python django unit-testing django-rest-framework factory


    【解决方案1】:

    您的ThankYouMessage 将有一个相关字段images 作为ThankYouImages 的集合,因此您需要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 仍然无法序列化并显示此错误:

    提交的数据不是文件。检查表单上的编码类型。

    但我认为这是另一个话题


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2022-12-05
      • 2022-01-03
      • 2023-01-02
      • 2020-11-12
      • 2020-07-11
      • 2019-02-04
      相关资源
      最近更新 更多