在Django序列化器中使用update()方法时,ImageField未更新

wyyhbhjk  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(167)

我想给予管理员能够更新与产品记录关联的图像。我有一个编辑类,允许管理员更新记录的各种元素,除了图像字段外,所有元素都正确更新。问题是上传图像在创建中有效,但在更新中无效。

型号

image1 = models.ImageField(db_column='product_image1', null=True, blank=True, upload_to='media/images/')

串行器

class products_update(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields =['category','product_name','description','unit_price','dis_price','image1','image2','image3']

浏览次数

Product.objects.create(product_name=productname,
                            description=description, quantity=quantity, unit_price=unitprice,
                            dis_price=discountprice,user=usertable, category=categoryid, image1=image1)

图像已成功上载到介质文件夹,路径存储在数据库中。
推杆

Product.objects.filter(id=pid, user=userdata).update(category = category, product_name=productname, description=description,unit_price=unitprice, dis_price=discountprice, image1=image1

当我使用更新方法时,图像路径存储在DB中,但图像未存储在媒体文件夹中。
有谁知道如何解决这个问题吗

xriantvc

xriantvc1#

<queryset>.update(...)只对 queryset 添加了一种注解,只影响SQL查询生成,不调用model.save方法。但只有model.save操作模型示例,并调用字段的save方法,该方法到达文件存储。queryset(<model>.objects.filter().update())不能对文件存储做任何事情。
因此,您应该示例化模型示例并保存它,而不是编写一个 update query。DRF文档中有实现保存示例的序列化程序的示例(作为模型示例,而不是直接的DB更新)
您使用了ModelSerializer,默认情况下它在update方法实现中调用instance.save,因此不清楚您是如何实现的。只需按照文档操作,然后让model.save发生。

相关问题