10

How to create a double field in mysql using django models. i run into this error and also how to create a longtext datatype with django

class Test(models.Model):
   maxcount = models.DoubleField(null=True) ## double DEFAULT NULL,
   cs = models.TextField()#longtext,

Error:

    maxcount = models.DoubleField(null=True) ##double DEFAULT NULL,
    AttributeError: 'module' object has no attribute 'DoubleField'
Rajeev
  • 44,985
  • 76
  • 186
  • 285

3 Answers3

15

There is no DoubleField in Django but FloatField [FloatField description in Django's Model field reference] creates a double datatype in mysql.

Django's TextField creates a LONGTEXT type in mysql. There is no easy way to change TextField behaviour to create e.g. MEDIUMTEXT type in mysql. But one can create a custom model field to achieve that: Writing custom model fields

Andrey Grachev
  • 1,259
  • 1
  • 14
  • 22
  • what about tiny int? models.SmallIntegerField create small int and how to create float field in this case – Rajeev Sep 11 '15 at 05:56
8

https://docs.djangoproject.com/en/1.8/ref/models/fields/#bigintegerfield
https://docs.djangoproject.com/en/1.8/ref/models/fields/#decimalfield
https://docs.djangoproject.com/en/dev/ref/models/fields/#floatfield

Use big int in a case when you want an Integer and decimal field.
Use https://docs.djangoproject.com/en/1.8/ref/models/fields/#charfield for Char field and set max and min parameters

GrvTyagi
  • 4,231
  • 1
  • 33
  • 40
  • what about tiny int?models.SmallIntegerField create small int and how to create float field in this case – Rajeev Sep 11 '15 at 05:56
  • Like a PositiveIntegerField, but only allows values under a certain (database-dependent) point. Values from 0 to 32767 are safe in all databases supported by Django and in case if you want to use flot use FloatField : FloatField uses Python’s float type internally – GrvTyagi Sep 11 '15 at 06:03
  • Hmm, Alternativelity i think the coumentation could have been much better in this case.Ty – Rajeev Sep 11 '15 at 06:06
  • It seems like part of the text here is missing. – Blairg23 Jan 27 '18 at 00:16
1

I think you might be needing DecimalField: https://docs.djangoproject.com/en/2.0/ref/models/fields/#decimalfield. It works well with MySQL, and you could also use this for integer values.

Declare the fields in your models

balance = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00))

Also, consider defining a decimal context to create your actual values like so:

# defined in the settings.py file.
DECIMAL_CONTEXT = Context(prec=6, rounding=ROUND_DOWN)

This will ensure compatible decimal objects through your application, and create values like this:

DECIMAL_CONTEXT.create_decimal(0)
DECIMAL_CONTEXT.create_decimal(500)
DECIMAL_CONTEXT.create_decimal(5)
DECIMAL_CONTEXT.create_decimal(0.50)
coya
  • 264
  • 2
  • 15