一次在模型中保存两个文件字段
我有一个包含 3 个文件字段的模型,并在调用 .save 时操作它们。问题是保存任何 FileField 都会触发对象的 .save。如何才能同时保存多个文件字段?
class Record(Model):
name = CharField(max_length=30)
audio = FileField(upload_to=settings.AUDIO_ROOT)
alt_audio = FileField(upload_to=settings.AUDIO_ROOT, null=True)
sample = FileField(upload_to=settings.AUDIO_ROOT, null=True)
def save(self, *args, **kwargs):
convert_files(self)
super(Record, self).save(*args, **kwargs)
上传音频 (mp3) 时,它会从 mp3 转换为 ogg(反之亦然),并保存到 alt_audio 和样本中:
def convert_files(record):
...
record.alt_audio.save(os.path.basename(convert_to), File(open(convert_to)))
record.sample.save(os.path.basename(sample_name), File(open(sample_name, 'r')))
问题是 alt_audio.save
触发回 record .保存
。我添加了每个文件字段的检查(如果它不为空)。我还想通过稍后将其交给 celery 服务器来推迟该操作。有没有办法不多次触发.save?
I have a model with 3 file fields, and manipulate them when .save is called. The problem is that saving any FileField triggers .save of the object. What can I do to save several FileFields at once?
class Record(Model):
name = CharField(max_length=30)
audio = FileField(upload_to=settings.AUDIO_ROOT)
alt_audio = FileField(upload_to=settings.AUDIO_ROOT, null=True)
sample = FileField(upload_to=settings.AUDIO_ROOT, null=True)
def save(self, *args, **kwargs):
convert_files(self)
super(Record, self).save(*args, **kwargs)
When the audio is uploaded (mp3), it's converted from mp3 to ogg (or vice-versa), which is saved into alt_audio and sample:
def convert_files(record):
...
record.alt_audio.save(os.path.basename(convert_to), File(open(convert_to)))
record.sample.save(os.path.basename(sample_name), File(open(sample_name, 'r')))
The problem is that alt_audio.save
triggers back record.save
. I had add checks of each filefield if it is not empty. I also want to postpone the action by giving it to celery server later. Is there a way to not trigger .save multiple times?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用 save 时有一个可选参数。默认情况下,会触发 commit,但如果执行 record.audio.save("audiofile.mp3", File(open(path_to_audio)), False),则不会触发 save 方法。
There is an optional parameter when you call save. By default, commit is triggered, but if you do record.audio.save("audiofile.mp3", File(open(path_to_audio)), False), save method won't be triggered.
使用.update,当仅在数据库上时,它不会触发任何内容
Use .update, it will not trigger anything, when only on the database