Last active
December 2, 2019 00:55
-
-
Save DataGreed/1ba46ca7387950abba2ff53baf70fec2 to your computer and use it in GitHub Desktop.
Django: update audio duration in database if the associated audio file was updated by user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# considering model has audio_field = FileField() | |
def some_pre_save_receiver(sender, instance, raw, using, update_fields, **kwargs): | |
file_was_updated = False | |
if hasattr(instance.audio_file, 'file') and isinstance(instance.audio_file.file, UploadedFile): | |
file_was_updated = True | |
if update_fields and "audio_file" in update_fields: | |
file_was_updated = True | |
print(f">> pre_save receiver executed, update fields: {update_fields}, file_was_updated: {file_was_updated}") | |
if file_was_updated: | |
# read audio file metadata | |
audio_info = mutagen.File(instance.audio_file).info | |
# set audio duration in seconds, so we can access it in database | |
instance.duration_seconds = int(audio_info.length) | |
print(">> audio duration was was updated") | |
else: | |
print(">> file not changed - duration was NOT updated") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment