trpt4him
trpt4him

Reputation: 1906

Convert one QuerySet element in all objects from int to Decimal

I am using Django. I'm working on a view function to try to show a list of budget transactions from my database along with other info like date, category, and a description. (Transaction is my model, so they're Transaction objects.) The transaction amounts are stored in integer format in the db (following some suggestions I saw here), as currency was supposedly easier to handle converting to int and back to decimal. (Now I'm not so sure.) I'm trying to convert back to decimal before sending the set of objects to a template for display. I can't figure out how to pull the amount out of each Transaction object, convert it to decimal, and get it back into the objects. I'm trying to do something like this:

object_list = Transaction.objects.all()

for obj in range(0,object_list.count()):
    object_list[obj].dec_amount = Decimal(object_list[obj].amount/100).quantize(Decimal('0.01'))

And the template, very simple for now:

{% for item in object_list %}

<tr>
<td>{{ item.dec_amount }}</td>
<td>{{ item.category }}</td>
<td>{{ item.date }}</td>

</tr>

{% endfor %}

I'm basically trying to create a new dec_amount attribute in each object, but I don't know if that works. The dec_amount is not available in my template. I also just think there must be a more elegant way to iterate over the objects to update their amount or create a new attribute with the decimal value. Or, maybe there's a more efficient way with pulling the QuerySet, but I don't see how I can easily keep the rows together between two queries that way. How can I use a loop to modify one attribute in every object of a QuerySet?

Thanks for any help. I gotta say, I'm getting frustrated -- coming from PHP, the whole Decimal thing seems more complicated.

EDIT: Tried to improve my terminology a bit.

Upvotes: 1

Views: 1459

Answers (2)

sneawo
sneawo

Reputation: 3631

The answer of Jesse the Game is right. You can also rewrite your loop as:

for obj in object_list:
    obj.dec_amount = Decimal(object_list[obj].amount/100).quantize(Decimal('0.01'))

Upvotes: 1

Jesse the Game
Jesse the Game

Reputation: 2630

If you just need to access the decimal value in templates, you could consider a property like this:

class Transaction(models.Model):
    @property
    def dec_amount(self):
        return Decimal(self.amount / 100).quantize(Decimal('0.01'))

Upvotes: 2

Related Questions