Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
  • Loading branch information...
commit 910bbe8f1fab2d8c9be22d056ec811d2a1085a91 1 parent 07dd6b2
Adrian Holovaty authored July 20, 2007

Showing 1 changed file with 38 additions and 0 deletions. Show diff stats Hide diff stats

  1. 38  docs/model-api.txt
38  docs/model-api.txt
@@ -1052,6 +1052,44 @@ create your tables. It's not called at any other time, so it can afford to
1052 1052
 execute slightly complex code, such as the ``DATABASE_ENGINE`` check in the
1053 1053
 above example.
1054 1054
 
  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
+
1055 1093
 Meta options
1056 1094
 ============
1057 1095
 

0 notes on commit 910bbe8

Please sign in to comment.
Something went wrong with that request. Please try again.