I use:
duration = float(ffmpeg.probe(audio_path)["format"]["duration"])
I collect an audio/video’s length and want to store it using my models. Should I use models.DecimalField()
or models.FloatField()
?
I use it to calculate and store a credit/cost in my model using
credit = models.DecimalField(max_digits=20, decimal_places=4)
1
When storing a duration value, especially when it’s related to calculations, such as calculating credits or costs, it’s generally better to use DecimalField
in Django. This is because DecimalField
allows you to control both the precision and scale(number of decimal places) explicitly, ensuring that you don’t encounter rounding errors that can occur with floating-point arithmetic.
Precision: DecimalField
is stored as a fixed-precision decimal, making it much more accurate than a FloatField
for calculations where precision is important (such as financial calculations or accumulating small values).
Consistency: If you’re already using DecimalField
for your credit field using it for the duration ensures that your calculations involving both fields are consistent and accurate.
Code example.
from django.db import models
class YourModel(models.Model):
duration = models.DecimalField(max_digits=10, decimal_places=4)
credit = models.DecimalField(max_digits=20, decimal_places=4)
max_digits=10
: This defines the total number of digits the field can have, including digits before and after the decimal point.decimal_places=4
: This defines how many digits can be stored after the decimal point.
I think the most sensical way is to use a DurationField
model field [Django-doc]. Django will look what database the backend uses, and try to work with the most sensical column type the database offers:
class MyModel(models.Model):
duration = models.DurationField()
and work with:
from datetime import timedelta
MyModel.objects.create(
duration=timedelta(
seconds=float(ffmpeg.probe(audio_path)['format']['duration'])
)
)