It is supposed the aggregation on integer is fast than numeric type in database duo to how they are stored as numeric is represented as string. As money only have 2 decimal place, it can be converted to an Integer despite of its decimal point.
The python class decimal.Decimal also has a shortcoming that it is not json serializable(neither cjson nor simplejson). This money field appears as a float number to the front end, so it does not meet the headache as DecimalField.
The usage is very simple.
In Model:
class SomeModel(models.Model):
...
income = MoneyField('income')
...
Then treat the attribute of the model instance as a normal float type.
Notes
If you try to use aggregation on this field, you have to convert it to float by yourself. Currently I could not find any method to fix this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from django.db import models
class MoneyField(models.IntegerField):
__metaclass__ = models.SubfieldBase
def get_db_prep_value(self, value):
if value is None:
return None
return int(value * 100)
def to_python(self, value):
if value is None or isinstance(value, float):
return value
try:
return float(value) / 100
except (TypeError, ValueError):
raise exceptions.ValidationError(
"This value must be an integer or a string represents an integer.")
def formfield(self, **kwargs):
from django.forms import FloatField
defaults = {'form_class': FloatField}
defaults.update(kwargs)
return super(MoneyField, self).formfield(**defaults)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.