Skip to content

Commit 910bbe8

Browse files
Added some additional docs to docs/model-api.txt db_type() section
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5736 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 07dd6b2 commit 910bbe8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/model-api.txt

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,6 +1052,44 @@ create your tables. It's not called at any other time, so it can afford to
10521052
execute slightly complex code, such as the ``DATABASE_ENGINE`` check in the
10531053
above example.
10541054

1055+
Some database column types accept parameters, such as ``CHAR(25)``, where the
1056+
parameter ``25`` represents the maximum column length. In cases like these,
1057+
it's more flexible if the parameter is specified in the model rather than being
1058+
hard-coded in the ``db_type()`` method. For example, it wouldn't make much
1059+
sense to have a ``CharMaxlength25Field``, shown here::
1060+
1061+
# This is a silly example of hard-coded parameters.
1062+
class CharMaxlength25Field(models.Field):
1063+
def db_type(self):
1064+
return 'char(25)'
1065+
1066+
# In the model:
1067+
class MyModel(models.Model):
1068+
# ...
1069+
my_field = CharMaxlength25Field()
1070+
1071+
The better way of doing this would be to make the parameter specifiable at run
1072+
time -- i.e., when the class is instantiated. To do that, just implement
1073+
``__init__()``, like so::
1074+
1075+
# This is a much more flexible example.
1076+
class BetterCharField(models.Field):
1077+
def __init__(self, maxlength, *args, **kwargs):
1078+
self.maxlength = maxlength
1079+
super(BetterCharField, self).__init__(*args, **kwargs)
1080+
1081+
def db_type(self):
1082+
return 'char(%s)' % self.maxlength
1083+
1084+
# In the model:
1085+
class MyModel(models.Model):
1086+
# ...
1087+
my_field = BetterCharField(25)
1088+
1089+
Note that if you implement ``__init__()`` on a ``Field`` subclass, it's
1090+
important to call ``Field.__init__()`` -- i.e., the parent class'
1091+
``__init__()`` method.
1092+
10551093
Meta options
10561094
============
10571095

0 commit comments

Comments
 (0)