gpt4 book ai didi

django storages aws s3 从模型记录中删除文件

转载 作者:行者123 更新时间:2023-12-04 13:36:41 25 4
gpt4 key购买 nike

我的 django aws S3 解决方案基于 https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html .

现在我试图找到一种方法来删除包含 S3 文件的模型中的一行。我可以使用 .delete() 删除该行,但它不会在 S3 中删除。

如何使删除行也在 S3 中删除?

下面是我的代码:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['POST'])
def delete_employee(request):
# ----- YAML below for Swagger -----
"""
description: This API deletes employee
parameters:
- name: employee_id
type: integer
required: true
location: form
"""
employee_id = request.POST['employee_id']
employee = Employee.objects.get(id = employee_id)
logging.debug(f"API employee username {employee.username}")
employee.delete() <---------- here is where the delete row happens
return Response("Employee Deleted!", status=status.HTTP_200_OK)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
company = models.ForeignKey(Company)
username = models.CharField(max_length=30, blank=False)
upload = models.FileField(blank=True) <--- S3 field

https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py (AWS 设置)
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}

DEFAULT_FILE_STORAGE = 'railercomapp.storage_backends.MediaStorage'

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py
从 storages.backends.s3boto3 导入 S3Boto3Storage
class MediaStorage(S3Boto3Storage):
location = 'media/yy'
file_overwrite = False

最佳答案

您必须明确删除该文件。你可以写一个 post delete signal或在 delete_employee 中进行功能。

employee.upload.delete(save=False)  # delete file
employee.delete() # delete model instance
FileField.delete() 的文档解释了这一点。

Note that when a model is deleted, related files are not deleted. If you need to cleanup orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).


您还应该确保在删除之前没有其他 FileField 引用完全相同的文件。

关于django storages aws s3 从模型记录中删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47377172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com