mrhaoji
mrhaoji

Reputation: 336

How to get the float result with certain precision in the F() expressions of Django queryset

addon_income = round(pendingAmount*0.1, 2)
print(addon_income)  # if pendingAmount = 6, addon_income = 0.6 which is ok here

Wallet.objects.filter(id=###).update(
    active=F('active')+addon_income, total=F('total')+addon_income,
    uddate_time=timezone.now()
)

In the queryset above, if the F('active') = 41.2, F('total') = 41.2, and addon_income = 0.6, the active and total becomes 41.800000000000004 and 41.800000000000004 after the updating.

I tried to use round() in the queryset as shown below:

Wallet.objects.filter(id=###).update(
    active=round(F('active')+addon_income, 2), total=round(F('total')+addon_income, 2),
    uddate_time=timezone.now()
)

but it returns error: type CombinedExpression doesn't define round method

Anyone has any suggestion? Thx!

Upvotes: 0

Views: 466

Answers (2)

mrhaoji
mrhaoji

Reputation: 336

I tried the solution in this post: Django ORM how to Round an Avg result

class Round(Func):
  function = 'ROUND'
  arity = 2

Book.objects.all().aggregate(Round(Avg('price'), 2))

Upvotes: 1

blue note
blue note

Reputation: 29081

Django has a Cast function that use can use in queries. In that function, you can specify FloatField(decimal_places=2)

Upvotes: 0

Related Questions