Django: How to use float precision instead of double precision in MySQL
models.FloatField
creates a double in MySQL.
The justification is similar to t开发者_开发百科hat of having SmallIntegerField.
Well there is a better way than that and a much easier one. I also wanted the same thing with my db, when I came across the following db_type() method in django.
First, you need to create a custom Field in django by inheriting the Field class
class customFloatField(models.Field):
def db_type(self,connection):
return 'float'
then you could use this as any other model field in your model class
number = customFloatField(null=True,blank=True)
I tried and this does work for me in MySQL. To change it as per the connection type, you would have to check the connection setting in an if statement and change accordingly.
More about this is mentioned in https://docs.djangoproject.com/en/dev/howto/custom-model-fields/
There are a few options to do this, but I don't understand why you would want to.
- Change it in the database, won't work when recreating the tables but Django won't do a manual cast so if the database changes, so do the results.
- Create a custom fieldtype (i.e. inherit
FloatField
and changeget_internal_type()
so it returns something likeSinglePrecisionFloatField
. After that you will also need to create your own database backend and add your custom type tocreation.DatabaseCreation.data_types
(source: http://code.djangoproject.com/browser/django/trunk/django/db/backends/mysql/creation.py) - Change every
FloatField
to single precision. Like above you would have to create your own database backend and/or change theFloatField
implementation in the current one.
精彩评论