我有一个这样的Django模型:
class Todo(models.Model):
big_file = models.FileField(blank=True)
status = models.PositiveSmallIntegerField(default=0)
progress = models.IntegerField(default=0)
我想做两个操作:
- 首先制作一个空的zipfile
big_file
(不太重要) - 然后逐步将文件添加到我的 zipfile 中(并迭代保存)
整个过程如下所示:
from django.core.files.base import File
import io, zipfile
def generate_data(todo):
io_bytes = io.BytesIO(b'')
# 1. save an empty Zip archive:
with zipfile.ZipFile(io_bytes, 'w') as zip_fd:
todo.generated_data.save('heavy_file.zip', File(zip_fd))
# 2. Progressively fill the Zip archive:
with zipfile.ZipFile(io_bytes, 'w') zip_fd:
for filename, data_bytes in long_iteration(todo):
with zip_fd.open(filename, 'w') as in_zip:
in_zip.write(data_bytes)
if condition(something):
todo.generated_data.save() # that does not work
todo.status = 1
todo.progress = 123
todo.save()
todo.status = 2
todo.save()
但我无法找出正确的文件描述符/类文件对象/文件路径/django-File对象组合......而且似乎在django中我总是必须 save(filename, content)
. 但是我的内容可能是千兆字节,所以将它全部存储到“内容”变量中听起来不合理?