[Fixed]-Django – How to get the value of a decimal field of object

1πŸ‘

βœ…

If I understood your problem correctly you need to filter objects in Hours table and update it value.

First of all note that this result = Hours.objects.filter(fullname=fullname).values('hours') return list of dicts, not list of Decimal. So if you need to get hours you should do this hour = result[0].get('hours'). But after this you cannot do hours = hours + 1.5. Because hours has Decimal type and you should to convert 1.5 which is float to Decimal first:

import decimal

result = Hours.objects.filter(fullname=fullname).values('hours')
hour = result[0].get('hours')
hour_difference = decimal.Decimal(1.5)
hour = hour + hour_difference 

But with Django you can make updates much easier. Just use update:

    Hours.objects.filter(fullname=fullname).update(hours=20.5)

If you need to increment current value then you can do it with F expression:

from django.db.models import F

Hours.objects.filter(fullname=fullname).update(hours=F('hours') + 1.5)

this will get all Hours object related with filter add to it’s hours field 1.5 and save it.

Leave a comment