Changeset 6792
- Timestamp:
- 12/01/07 11:29:45 (9 months ago)
- Files:
-
- django/trunk/docs/custom_model_fields.txt (modified) (26 diffs)
- django/trunk/docs/templates.txt (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk/docs/custom_model_fields.txt
r6677 r6792 1 1 =================== 2 Custom Model Fields2 Custom model fields 3 3 =================== 4 4 … … 9 9 10 10 The `model reference`_ documentation explains how to use Django's standard 11 field classes. For many purposes, those classes are all you'll need. Sometimes, 12 though, the Django version won't meet your precise requirements, or you'll want 13 to use a field that is entirely different from those shipped with Django. 11 field classes -- ``CharField``, ``DateField``, etc. For many purposes, those 12 classes are all you'll need. Sometimes, though, the Django version won't meet 13 your precise requirements, or you'll want to use a field that is entirely 14 different from those shipped with Django. 14 15 15 16 Django's built-in field types don't cover every possible database column type -- … … 28 29 easier to follow, we'll use a consistent example throughout this document. 29 30 Suppose you have a Python object representing the deal of cards in a hand of 30 Bridge_. It doesn't matter if you don't know how to play Bridge. You only need31 to know that 52 cards are dealt out equally to four players, who are 32 traditionally called *north*, *east*, *south* and *west*. Our class looks 33 something like this::31 Bridge_. (Don't worry, you don't know how to play Bridge to follow this 32 example. You only need to know that 52 cards are dealt out equally to four 33 players, who are traditionally called *north*, *east*, *south* and *west*.) 34 Our class looks something like this:: 34 35 35 36 class Hand(object): … … 43 44 # ... (other possibly useful methods omitted) ... 44 45 45 This is just an ordinary Python class, nothing Django-specific about it. We 46 would like to be able to things like this in our models (we assume the 47 ``hand`` attribute on the model is an instance of ``Hand``):: 48 46 This is just an ordinary Python class, with nothing Django-specific about it. 47 We'd like to be able to things like this in our models (we assume the ``hand`` 48 attribute on the model is an instance of ``Hand``):: 49 49 50 50 example = MyModel.objects.get(pk=1) … … 73 73 .. _Bridge: http://en.wikipedia.org/wiki/Contract_bridge 74 74 75 Background Theory75 Background theory 76 76 ================= 77 77 … … 88 88 column type. Different databases provide different sets of valid column types, 89 89 but the rule is still the same: those are the only types you have to work 90 with. Anything you want to store in the database must fit into one of90 with. Anything you want to store in the database must fit into one of 91 91 those types. 92 92 … … 96 96 97 97 For our ``Hand`` example, we could convert the card data to a string of 104 98 characters by concatenating all the cards together in a pre-determined order. 99 Say, all the *north* cards first, then the *east*, *south* and *west* cards, in 100 that order. So ``Hand`` objects can be saved to text or character columns in 101 the database. 98 characters by concatenating all the cards together in a pre-determined order -- 99 say, all the *north* cards first, then the *east*, *south* and *west* cards. So 100 ``Hand`` objects can be saved to text or character columns in the database. 102 101 103 102 What does a field class do? … … 110 109 and so forth. Storing all that information is handled by ``Field``. We'll get 111 110 into the precise details of what ``Field`` can do later on; for now, suffice it 112 to say that everything descends from ``Field`` and then customi ses key pieces113 of the class behavio ur.111 to say that everything descends from ``Field`` and then customizes key pieces 112 of the class behavior. 114 113 115 114 .. _form fields: ../newforms/#fields 116 115 117 It's important to reali se that a Django field class is not what is stored in116 It's important to realize that a Django field class is not what is stored in 118 117 your model attributes. The model attributes contain normal Python objects. The 119 118 field classes you define in a model are actually stored in the ``Meta`` class … … 128 127 instances and the database/serializer values in various ways (there are 129 128 differences between storing a value and using a value for lookups, for 130 example). If this sounds a bit tricky, don't worry. It will hopefully become 131 clearer in the examples below. Just remember that you will often end up 132 creating two classes when you want a custom field. The first class is the 133 Python object that your users will manipulate. They will assign it to the model 134 attribute, they will read from it for displaying purposes, things like that. 135 This is the ``Hand`` class in our example. The second class is the ``Field`` 136 subclass. This is the class that knows how to convert your first class back and 137 forth between its permanent storage form and the Python form. 129 example). If this sounds a bit tricky, don't worry -- it will become clearer in 130 the examples below. Just remember that you will often end up creating two 131 classes when you want a custom field: 132 133 * The first class is the Python object that your users will manipulate. 134 They will assign it to the model attribute, they will read from it for 135 displaying purposes, things like that. This is the ``Hand`` class in our 136 example. 137 138 * The second class is the ``Field`` subclass. This is the class that knows 139 how to convert your first class back and forth between its permanent 140 storage form and the Python form. 138 141 139 142 Writing a ``Field`` subclass 140 143 ============================= 141 144 142 When you are planning your ``Field`` subclass, first give some thought to 143 which existing field your new field is most similar to. Can you subclass an 144 existing Django field and save yourself some work? If not, you should subclass the ``Field`` class, from which everything is descended. 145 146 Initialising your new field is a matter of separating out any arguments that 145 When planning your ``Field`` subclass, first give some thought to which 146 existing ``Field`` class your new field is most similar to. Can you subclass an 147 existing Django field and save yourself some work? If not, you should subclass 148 the ``Field`` class, from which everything is descended. 149 150 Initializing your new field is a matter of separating out any arguments that 147 151 are specific to your case from the common arguments and passing the latter to 148 152 the ``__init__()`` method of ``Field`` (or your parent class). 149 153 150 In our example, the Django field we create is going to be called 151 ``HandField``. It's not a bad idea to use a similar naming scheme to Django's 152 fields so that our new class is identifiable and yet clearly related to the 153 ``Hand`` class it is wrapping. It doesn't behave like any existing field, so 154 we'll subclass directly from ``Field``:: 154 In our example, we'll call our field ``HandField``. (It's a good idea to call 155 your ``Field`` subclass ``(Something)Field``, so it's easily identifiable as a 156 ``Field`` subclass.) It doesn't behave like any existing field, so we'll 157 subclass directly from ``Field``:: 155 158 156 159 from django.db import models … … 161 164 super(HandField, self).__init__(*args, **kwargs) 162 165 163 Our ``HandField`` willaccept most of the standard field options (see the list166 Our ``HandField`` accept most of the standard field options (see the list 164 167 below), but we ensure it has a fixed length, since it only needs to hold 52 165 168 card values plus their suits; 104 characters in total. … … 172 175 this case. 173 176 174 This behavio ur simplifies the field classes, because they don't need to177 This behavior simplifies the field classes, because they don't need to 175 178 check for options that aren't necessary. They just pass all the options to 176 the parent class and then don't use them later on. It is up to you whether179 the parent class and then don't use them later on. It's up to you whether 177 180 you want your fields to be more strict about the options they select, or 178 to use the simpler, more permissive behavio ur of the current fields.181 to use the simpler, more permissive behavior of the current fields. 179 182 180 183 The ``Field.__init__()`` method takes the following parameters, in this 181 184 order: 182 185 183 -``verbose_name``184 -``name``185 -``primary_key``186 -``max_length``187 -``unique``188 -``blank``189 -``null``190 -``db_index``191 -``core``192 -``rel``: Used for related fields (like ``ForeignKey``). For advanced use186 * ``verbose_name`` 187 * ``name`` 188 * ``primary_key`` 189 * ``max_length`` 190 * ``unique`` 191 * ``blank`` 192 * ``null`` 193 * ``db_index`` 194 * ``core`` 195 * ``rel``: Used for related fields (like ``ForeignKey``). For advanced use 193 196 only. 194 -``default``195 -``editable``196 -``serialize``: If ``False``, the field will not be serialized when the197 * ``default`` 198 * ``editable`` 199 * ``serialize``: If ``False``, the field will not be serialized when the 197 200 model is passed to Django's serializers_. Defaults to ``True``. 198 -``prepopulate_from``199 -``unique_for_date``200 -``unique_for_month``201 -``unique_for_year``202 -``validator_list``203 -``choices``204 -``radio_admin``205 -``help_text``206 -``db_column``207 -``db_tablespace``: Currently only used with the Oracle backend and only201 * ``prepopulate_from`` 202 * ``unique_for_date`` 203 * ``unique_for_month`` 204 * ``unique_for_year`` 205 * ``validator_list`` 206 * ``choices`` 207 * ``radio_admin`` 208 * ``help_text`` 209 * ``db_column`` 210 * ``db_tablespace``: Currently only used with the Oracle backend and only 208 211 for index creation. You can usually ignore this option. 209 212 … … 219 222 220 223 As we indicated in the introduction_, field subclasses are often needed for 221 two reasons . Either to take advantage of a custom database column type, or to222 handle complex Python types. A combination of the two is obviouslyalso223 possible. If you are only working with custom database column types and your224 two reasons: either to take advantage of a custom database column type, or to 225 handle complex Python types. Obviously, a combination of the two is also 226 possible. If you're only working with custom database column types and your 224 227 model fields appear in Python as standard Python types direct from the 225 228 database backend, you don't need to worry about this section. 226 229 227 If you are handling custom Python types, such as our ``Hand`` class, we need228 to make sure that when Django initiali ses an instance of our model and assigns229 a database value to our custom field attribute we convert that value into the230 If you're handling custom Python types, such as our ``Hand`` class, we need 231 to make sure that when Django initializes an instance of our model and assigns 232 a database value to our custom field attribute, we convert that value into the 230 233 appropriate Python object. The details of how this happens internally are a 231 little complex. For the field writer, though, things are fairly simple. Make 232 sure your field subclass uses ``django.db.models.SubfieldBase`` as its 233 metaclass. This ensures that the ``to_python()`` method, documented below_, 234 will always be called when the attribute is initialised. 235 236 Our ``HandField`` class now looks like this:: 234 little complex, but the code you need to write in your ``Field`` class is 235 simple: make sure your field subclass uses ``django.db.models.SubfieldBase`` as 236 its metaclass:: 237 237 238 238 class HandField(models.Field): … … 242 242 # ... 243 243 244 This ensures that the ``to_python()`` method, documented below_, will always be 245 called when the attribute is initialized. 246 244 247 .. _below: #to-python-self-value 245 248 … … 247 250 -------------- 248 251 249 Once you've created your ``Field`` subclass and setup up the 250 ``__metaclass__``, if necessary, there are a few standard methods you need to 251 consider overriding. Which of these you need to implement will depend on you 252 particular field behaviour. The list below is in approximately decreasing 253 order of importance, so start from the top. 252 Once you've created your ``Field`` subclass and set up up the 253 ``__metaclass__``, you might consider overriding a few standard methods, 254 depending on your field's behavior. The list of methods below is in 255 approximately decreasing order of importance, so start from the top. 254 256 255 257 ``db_type(self)`` … … 338 340 of the way. 339 341 340 341 342 ``to_python(self, value)`` 342 343 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 343 344 344 Converts between all the ways your field can receive its initial value and the 345 Python object you want to end up with. The default version just returns 346 ``value``, so is useful is the database backend returns the data already in 347 the correct form (a Python string, for example). 348 349 Normally, you will need to override this method. As a general rule, be 350 prepared to accept an instance of the right type (e.g. ``Hand`` in our ongoing 351 example), a string (from a deserializer, for example), and whatever the 352 database wrapper returns for the column type you are using. 353 354 In our ``HandField`` class, we are storing the data in a character field in 355 the database, so we need to be able to process strings and ``Hand`` instances 356 in ``to_python()``:: 345 Converts a value as returned by your database (or a serializer) to a Python 346 object. 347 348 The default implementation simply returns ``value``, for the common case in 349 which the database backend already returns data in the correct format (as a 350 Python string, for example). 351 352 If your custom ``Field`` class deals with data structures that are more complex 353 than strings, dates, integers or floats, then you'll need to override this 354 method. As a general rule, the method should deal gracefully with any of the 355 following arguments: 356 357 * An instance of the correct type (e.g., ``Hand`` in our ongoing example). 358 359 * A string (e.g., from a deserializer). 360 361 * Whatever the database returns for the column type you're using. 362 363 In our ``HandField`` class, we're storing the data as a VARCHAR field in the 364 database, so we need to be able to process strings and ``Hand`` instances in 365 ``to_python()``:: 366 367 import re 357 368 358 369 class HandField(models.Field): … … 363 374 return value 364 375 365 # The string case 376 # The string case. 366 377 p1 = re.compile('.{26}') 367 378 p2 = re.compile('..') … … 369 380 return Hand(*args) 370 381 371 Notice that we always return a ``Hand`` instance from this method. That is the372 Python object we want to store in the model's attribute.382 Notice that we always return a ``Hand`` instance from this method. That's the 383 Python object type we want to store in the model's attribute. 373 384 374 385 ``get_db_prep_save(self, value)`` … … 378 389 (as opposed to serialization). The ``value`` parameter is the current value of 379 390 the model's attribute (a field has no reference to its containing model, so it 380 cannot retrieve the value itself) and the method should return data in a391 cannot retrieve the value itself), and the method should return data in a 381 392 format that can be used as a parameter in a query for the database backend. 382 393 … … 389 400 return ''.join([''.join(l) for l in (self.north, 390 401 self.east, self.south, self.west)]) 391 392 402 393 403 ``pre_save(self, model_instance, add)`` … … 400 410 parameter will be ``True``, otherwise it will be ``False``. 401 411 402 Often you won't need to override this method. However, at times it can be very 403 useful. For example, the Django ``DateTimeField`` uses this method to set the 404 attribute to the correct value before returning it in the cases when 405 ``auto_now `` or ``auto_now_add`` are set on the field.412 You only need to override this method if you want to preprocess the value 413 somehow, just before saving. For example, Django's ``DateTimeField`` uses this 414 method to set the attribute correctly in the case of ``auto_now`` or 415 ``auto_now_add``. 406 416 407 417 If you do override this method, you must return the value of the attribute at … … 461 471 for the ``form_class`` argument and then delegate further handling to the 462 472 parent class. This might require you to write a custom form field (and even a 463 form widget). See the `forms documentation`_ for information about this . Also464 have a look at ``django.contrib.localflavor`` for some examples of custom 465 widgets.473 form widget). See the `forms documentation`_ for information about this, and 474 take a look at the code in ``django.contrib.localflavor`` for some examples of 475 custom widgets. 466 476 467 477 Continuing our ongoing example, we can write the ``formfield()`` method as:: … … 472 482 def formfield(self, **kwargs): 473 483 # This is a fairly standard way to set up some defaults 474 # whil stletting the caller override them.484 # while letting the caller override them. 475 485 defaults = {'form_class': MyFormField} 476 486 defaults.update(kwargs) 477 487 return super(HandField, self).formfield(**defaults) 478 488 479 This assumes we have some``MyFormField`` field class (which has its own480 default widget) imported. This document doesn't cover the details of writing481 custom formfields.489 This assumes we're imported a ``MyFormField`` field class (which has its own 490 default widget). This document doesn't cover the details of writing custom form 491 fields. 482 492 483 493 .. _helper functions: ../newforms/#generating-forms-for-models … … 491 501 simple cases. 492 502 493 If you have created a ``db_type()`` method, you do not need to worry about503 If you have created a ``db_type()`` method, you don't need to worry about 494 504 ``get_internal_type()`` -- it won't be used much. Sometimes, though, your 495 505 database storage is similar in type to some other field, so you can use that … … 513 523 ``None``. See the documentation of ``db_type()`` above_ for reasons why this 514 524 might be useful. Putting a descriptive string in as the type of the field for 515 the serializer is a useful idea if you are ever going to be using the525 the serializer is a useful idea if you're ever going to be using the 516 526 serializer output in some other place, outside of Django. 517 527 … … 529 539 version of the data. This method has some internal uses that aren't of 530 540 interest to use here (mostly having to do with manipulators). For our 531 purposes, it is sufficient to return a one item dictionary that maps the541 purposes, it's sufficient to return a one item dictionary that maps the 532 542 attribute name to a string. 533 543 … … 550 560 -------------------- 551 561 552 Writing a custom field can be a tricky process sometimes, particularly if you 553 are doing complex conversions between your Python types and your database and 554 serialization formats. A couple of tips to make things go more smoothly: 555 556 1. Look at the existing Django fields (in 557 ``django/db/models/fields/__init__.py``) for inspiration. Try to find a field 558 that is already close to what you want and extend it a little bit, in 559 preference to creating an entirely new field from scratch. 560 561 2. Put a ``__str__()`` or ``__unicode__()`` method on the class you are 562 wrapping up as a field. There are a lot of places where the default behaviour 563 of the field code is to call ``force_unicode()`` on the value (in our 564 examples in this document, ``value`` would be a ``Hand`` instance, not a 565 ``HandField``). So if your ``__unicode__()`` method automatically converts to 566 the string form of your Python object, you can save yourself a lot of work. 567 562 Writing a custom field can be a tricky process, particularly if you're doing 563 complex conversions between your Python types and your database and 564 serialization formats. Here are a couple of tips to make things go more 565 smoothly: 566 567 1. Look at the existing Django fields (in 568 ``django/db/models/fields/__init__.py``) for inspiration. Try to find a 569 field that's similar to what you want and extend it a little bit, 570 instead of creating an entirely new field from scratch. 571 572 2. Put a ``__str__()`` or ``__unicode__()`` method on the class you're 573 wrapping up as a field. There are a lot of places where the default 574 behavior of the field code is to call ``force_unicode()`` on the value. 575 (In our examples in this document, ``value`` would be a ``Hand`` 576 instance, not a ``HandField``). So if your ``__unicode__()`` method 577 automatically converts to the string form of your Python object, you can 578 save yourself a lot of work. django/trunk/docs/templates.txt
r6770 r6792 1278 1278 1279 1279 If used with a numeric integer argument, ``floatformat`` rounds a number to 1280 that many decimal places. For example:1280 that many decimal places. For example: 1281 1281 1282 1282 ======== ========================= ======
