一次在模型中保存两个文件字段

发布于 2024-10-16 08:01:52 字数 887 浏览 2 评论 0原文

我有一个包含 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌辣 2024-10-23 08:01:52

调用 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.

别在捏我脸啦 2024-10-23 08:01:52

使用.update,当仅在数据库上时,它不会触发任何内容

Record.objects.filter(pk=record.pk).update(field='new_value', field2='newvalue')

Use .update, it will not trigger anything, when only on the database

Record.objects.filter(pk=record.pk).update(field='new_value', field2='newvalue')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文