Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django DecimalField - how do I retrieve the value as a float?

So I never would have used Django's DecimalField option if I had known how difficult it would be to serialize my model data into JSON as a result.

Long story short, how do I get the float value from a DecimalField?

My model looks like this:

class DailyReport(models.Model):
    earnings = models.DecimalField(max_digits=12, decimal_places=4)

    def earnings_float(self):
        return self.earnings.to_float()

Obviously there is no to_float() method available, so what do I do instead?

BELOW IS LATER ADDITION:

This works:

class DailyReport(models.Model):
    earnings = models.DecimalField(max_digits=12, decimal_places=4)

    def earnings_float(self):
        return float(self.earnings)

But even this seems too complicated. I'm trying to use django-rest-framework for all the serializing, since I'm using it for rest-framework stuff in my app generally. In this particular case I'd just like to transform and serialize my data into python lists and dictionaries and then store them as documents in Mongo DB via pymongo 3.

like image 764
tadasajon Avatar asked Dec 14 '22 14:12

tadasajon


1 Answers

Just cast the DecimalField to a float:

def earnings_float(self):
        return float(self.earnings)
like image 87
Jeff K Avatar answered Jan 21 '23 15:01

Jeff K