Home > Net >  Is it possible to have flexible decimal_places for a model in django?
Is it possible to have flexible decimal_places for a model in django?

Time:02-10

I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals.

For example:

This is the class

class Asset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0)
    share_cost = models.DecimalField(max_digits=18, decimal_places=0, default=0) 

If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute."

Maybe what i am trying is not possíble, probably i need to find another solution. I am open to suggestions

I would like to know if is possíble to have this decimal places fleixible.

CodePudding user response:

Not sure if it is feasible to achieve what you described using a single field. Django maps model structure to the corresponding table in the database and the exact storage implementation there might vary depending on the database type you are using. That said shares_amount field type will remain constant and could be changed only through the migration. https://docs.djangoproject.com/en/4.0/ref/models/fields/#decimalfield

As an alternative, you could think of using a slightly different approach on how to store information. For example, have two nullable fields and fill for each category type with correct validation depending on the type. Or have a single field with the maximum possible number of the decimal places and round them to the desired precision where it is required.

CodePudding user response:

I found out a solution that worked for what i was wondering to achieve.

I chaged the field to a FloatField type, instead of DecimalField. Than i got more flexibilie on how many decimals, without restrictions:

shares_amount = models.FloatField() 

As there where using some mathemathic operations, started to show this conflict error:

*unsupported operand type(s) for : 'float' and 'decimal.Decimal'

The solution was here on the forum:

unsupported operand type(s) for *: 'float' and 'Decimal'

So for the mathematics it was just do that:

decimal.Decimal(self.shares_amount) * self.share_cost


  • Related