culebrón
culebrón

Reputation: 36513

Save two file filelds in a model at once

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?

Upvotes: 0

Views: 142

Answers (2)

fylb
fylb

Reputation: 699

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.

Upvotes: 3

programmersbook
programmersbook

Reputation: 4114

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

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

Upvotes: 1

Related Questions