Reputation: 1361
We have a mysql DB table that has attributes like:
+-----------------------+------------------+------+-----+-------------------+
| Field | Type | Null | Key | Default |
+-----------------------+------------------+------+-----+-------------------+
| age | int(1) | YES | | NULL |
| blah | int(1) | YES | | NULL |
I was curious about the int(1), and so referred to the docs, and here is a description:
M indicates the maximum display width for integer types.
The maximum legal display width is 255. Display width is
unrelated to the range of values a type can contain
[ . . . ]
Given that I want to preserve the current schema, is there a way in Django where we can specify display length of the models.*IntegerField
?
app/models.py:
from django.db import models
class Grade(models.Model):
type = models.SmallIntegerField(primary_key=True)
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
Here is the generated SQL:
> python manage.py sql app
BEGIN;
CREATE TABLE `app_grade` (
`type` smallint NOT NULL PRIMARY KEY,
`name` varchar(30) NOT NULL
)
;
COMMIT;
Edit: I came to know of the command manage.py inspectdb
that will generate model based on db tables present. For the table in question, the output for the column of type int(1)
is:
class table(models.Model):
[ . . . ]
columnx = models.IntegerField(null=True, db_column='columnX', blank=True) # Field name made lowercase.
[ . . . ]
So django considers int(M)
and IntegerField
the same. I am fine with it as long as no information/constraint is lost. What are the recommendations here?
Upvotes: 1
Views: 1766
Reputation: 33769
As the MySQL docs said, an INT
is an INT
. The display width doesn't affect the range of values that can be stored in the column or impose any other limitation on the values, so you don't need to take it into account. Display width for integer types really just affects display (and only for the limited set of things that actually respect it).
Now, the SQL that Django generated when you were using a SmallIntegerField
used SMALLINT
. SMALLINT
does have a different (smaller) range of possible values than INT
.
What's important here is that you preserve the data type, so use IntegerField
.
Upvotes: 1