Summary
I’m building a project in Django – and will many small-range positive decimal values (1.25, 0.01, etc). In the database (MySQL), it makes sense to store them as value*10^precision. This means instead of storing a float type (4 bytes), I can get away with a SmallInt(2 bytes). This is rad when it’s megabytes of data.
Problem
The issue is when Django and the PositiveSmallIntegerField() makes a widget that automatically checks for “whole number” values!
Option 1: Use a DecimalField() in the model code, and whenever the database changes, I update the SQL to be a SMALLINT(3).
PRECISION=2
class MyModule(models.Model):
...<fields>
def readySave(self):
pseudoDecimalField *= 10**PRECISION
def setValues(self):
pseudoDecimalField /= 10**PRECISION
def save(self):
# pre-save things here
self.readySave()
super(MyModule, self).save()
# post-save things here
self.setValues()
Option 2: Use raw SQL commands when pushing/pulling values.
Any opinions or experiences on the matter are much appreciated. Does anyone have any other ways to make this happen?
The problem is only in “frontend” part, so there must be a way to solve the problem without modifying database. The neatest way to do that is to overwrite widget for the field in form. It should look like that:
You can read more about widgets in great Django documentatin.