| | 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. |
|---|