Django

Code

Changeset 5736

Show
Ignore:
Timestamp:
07/20/07 16:24:30 (1 year ago)
Author:
adrian
Message:

Added some additional docs to docs/model-api.txt db_type() section

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/model-api.txt

    r5725 r5736  
    10521052execute slightly complex code, such as the ``DATABASE_ENGINE`` check in the 
    10531053above example. 
     1054 
     1055Some database column types accept parameters, such as ``CHAR(25)``, where the 
     1056parameter ``25`` represents the maximum column length. In cases like these, 
     1057it's more flexible if the parameter is specified in the model rather than being 
     1058hard-coded in the ``db_type()`` method. For example, it wouldn't make much 
     1059sense 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 
     1071The better way of doing this would be to make the parameter specifiable at run 
     1072time -- 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 
     1089Note that if you implement ``__init__()`` on a ``Field`` subclass, it's 
     1090important to call ``Field.__init__()`` -- i.e., the parent class' 
     1091``__init__()`` method. 
    10541092 
    10551093Meta options