开发者

Django: How to use float precision instead of double precision in MySQL

models.FloatField creates a double in MySQL.

Is it possible, and how, to create a float precision field instead of double precision?

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.

  1. 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.
  2. Create a custom fieldtype (i.e. inherit FloatField and change get_internal_type() so it returns something like SinglePrecisionFloatField. After that you will also need to create your own database backend and add your custom type to creation.DatabaseCreation.data_types (source: http://code.djangoproject.com/browser/django/trunk/django/db/backends/mysql/creation.py)
  3. Change every FloatField to single precision. Like above you would have to create your own database backend and/or change the FloatField implementation in the current one.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜