Django ORM - assigning a raw DecimalField value

CHANGE !!! - Casting a value to a string seems fine when I create a new object, but when I try to edit an existing object it doesn't allow it.

So I have a decimal field in one of my Decimal models (3,2)

When I query all of these objects and try to set this field:

fieldName = 0.85

      

OR

fieldName = .85

      

It will boil, "Can't convert float to DecimalField, try converting string first" ...

So I am doing:

fieldName = str(0.85)

      

the same error.

I even tried:

fieldName = "0.85"

      

The same mistakes. Am I in some kind of wire-frame error here or what? Note that when I actually go into Django Admin and manually edit the objects, it works great.

I am running Django 1.1 on Python 2.6

+2


source to share


2 answers


from decimal import Decimal
object.fieldName = Decimal("0.85")

      

or



f = 0.85
object.fieldName = Decimal(str(f))

      

+10


source


Django DecimalField is "... represented by python Decimal ." You may try:

>>> obj.fieldName = Decimal("0.85")

      



The behavior can also change depending on the database backed you are using. With sqlite, I can assign string values ​​to DecimalFields on new and existing objects without error.

+2


source







All Articles