Django

Code

Changeset 6792

Show
Ignore:
Timestamp:
12/01/07 11:29:45 (9 months ago)
Author:
adrian
Message:

Edited docs/custom_model_fields.txt from [6652]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/custom_model_fields.txt

    r6677 r6792  
    11=================== 
    2 Custom Model Fields 
     2Custom model fields 
    33=================== 
    44 
     
    99 
    1010The `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. 
     11field classes -- ``CharField``, ``DateField``, etc. For many purposes, those 
     12classes are all you'll need. Sometimes, though, the Django version won't meet 
     13your precise requirements, or you'll want to use a field that is entirely 
     14different from those shipped with Django. 
    1415 
    1516Django's built-in field types don't cover every possible database column type -- 
     
    2829easier to follow, we'll use a consistent example throughout this document. 
    2930Suppose 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 need 
    31 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:: 
     31Bridge_. (Don't worry, you don't know how to play Bridge to follow this 
     32example. You only need to know that 52 cards are dealt out equally to four 
     33players, who are traditionally called *north*, *east*, *south* and *west*.) 
     34Our class looks something like this:: 
    3435 
    3536    class Hand(object): 
     
    4344        # ... (other possibly useful methods omitted) ... 
    4445 
    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  
     46This is just an ordinary Python class, with nothing Django-specific about it. 
     47We'd like to be able to things like this in our models (we assume the ``hand`` 
     48attribute on the model is an instance of ``Hand``):: 
    4949 
    5050    example = MyModel.objects.get(pk=1) 
     
    7373.. _Bridge: http://en.wikipedia.org/wiki/Contract_bridge 
    7474 
    75 Background Theory 
     75Background theory 
    7676================= 
    7777 
     
    8888column type. Different databases provide different sets of valid column types, 
    8989but 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 of 
     90with. Anything you want to store in the database must fit into one of 
    9191those types. 
    9292 
     
    9696 
    9797For 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. 
     98characters by concatenating all the cards together in a pre-determined order -- 
     99say, 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. 
    102101 
    103102What does a field class do? 
     
    110109and so forth. Storing all that information is handled by ``Field``. We'll get 
    111110into the precise details of what ``Field`` can do later on; for now, suffice it 
    112 to say that everything descends from ``Field`` and then customises key pieces 
    113 of the class behaviour. 
     111to say that everything descends from ``Field`` and then customizes key pieces 
     112of the class behavior. 
    114113 
    115114.. _form fields: ../newforms/#fields 
    116115 
    117 It's important to realise that a Django field class is not what is stored in 
     116It's important to realize that a Django field class is not what is stored in 
    118117your model attributes. The model attributes contain normal Python objects. The 
    119118field classes you define in a model are actually stored in the ``Meta`` class 
     
    128127instances and the database/serializer values in various ways (there are 
    129128differences 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. 
     129example). If this sounds a bit tricky, don't worry -- it will become clearer in 
     130the examples below. Just remember that you will often end up creating two 
     131classes 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. 
    138141 
    139142Writing a ``Field`` subclass 
    140143============================= 
    141144 
    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 
     145When planning your ``Field`` subclass, first give some thought to which 
     146existing ``Field`` class your new field is most similar to. Can you subclass an 
     147existing Django field and save yourself some work? If not, you should subclass 
     148the ``Field`` class, from which everything is descended. 
     149 
     150Initializing your new field is a matter of separating out any arguments that 
    147151are specific to your case from the common arguments and passing the latter to 
    148152the ``__init__()`` method of ``Field`` (or your parent class). 
    149153 
    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``:: 
     154In our example, we'll call our field ``HandField``. (It's a good idea to call 
     155your ``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 
     157subclass directly from ``Field``:: 
    155158 
    156159    from django.db import models 
     
    161164            super(HandField, self).__init__(*args, **kwargs) 
    162165 
    163 Our ``HandField`` will accept most of the standard field options (see the list 
     166Our ``HandField`` accept most of the standard field options (see the list 
    164167below), but we ensure it has a fixed length, since it only needs to hold 52 
    165168card values plus their suits; 104 characters in total. 
     
    172175    this case. 
    173176 
    174     This behaviour simplifies the field classes, because they don't need to 
     177    This behavior simplifies the field classes, because they don't need to 
    175178    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 whether 
     179    the parent class and then don't use them later on. It's up to you whether 
    177180    you want your fields to be more strict about the options they select, or 
    178     to use the simpler, more permissive behaviour of the current fields. 
     181    to use the simpler, more permissive behavior of the current fields. 
    179182 
    180183The ``Field.__init__()`` method takes the following parameters, in this 
    181184order: 
    182185 
    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 use 
     186    * ``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 
    193196      only. 
    194     - ``default`` 
    195     - ``editable`` 
    196     - ``serialize``: If ``False``, the field will not be serialized when the 
     197    * ``default`` 
     198    * ``editable`` 
     199    * ``serialize``: If ``False``, the field will not be serialized when the 
    197200      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 only 
     201    * ``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 
    208211      for index creation. You can usually ignore this option. 
    209212 
     
    219222 
    220223As 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 to 
    222 handle complex Python types. A combination of the two is obviously also 
    223 possible. If you are only working with custom database column types and your 
     224two reasons: either to take advantage of a custom database column type, or to 
     225handle complex Python types. Obviously, a combination of the two is also 
     226possible. If you're only working with custom database column types and your 
    224227model fields appear in Python as standard Python types direct from the 
    225228database backend, you don't need to worry about this section. 
    226229 
    227 If you are handling custom Python types, such as our ``Hand`` class, we need 
    228 to make sure that when Django initialises an instance of our model and assigns 
    229 a database value to our custom field attribute we convert that value into the 
     230If you're handling custom Python types, such as our ``Hand`` class, we need 
     231to make sure that when Django initializes an instance of our model and assigns 
     232a database value to our custom field attribute, we convert that value into the 
    230233appropriate 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:: 
     234little complex, but the code you need to write in your ``Field`` class is 
     235simple: make sure your field subclass uses ``django.db.models.SubfieldBase`` as 
     236its metaclass:: 
    237237 
    238238    class HandField(models.Field): 
     
    242242            # ... 
    243243 
     244This ensures that the ``to_python()`` method, documented below_, will always be 
     245called when the attribute is initialized. 
     246 
    244247.. _below: #to-python-self-value 
    245248 
     
    247250-------------- 
    248251 
    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. 
     252Once you've created your ``Field`` subclass and set up up the 
     253``__metaclass__``, you might consider overriding a few standard methods, 
     254depending on your field's behavior. The list of methods below is in 
     255approximately decreasing order of importance, so start from the top. 
    254256 
    255257``db_type(self)`` 
     
    338340of the way. 
    339341 
    340  
    341342``to_python(self, value)`` 
    342343~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    343344 
    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()``:: 
     345Converts a value as returned by your database (or a serializer) to a Python 
     346object. 
     347 
     348The default implementation simply returns ``value``, for the common case in 
     349which the database backend already returns data in the correct format (as a 
     350Python string, for example). 
     351 
     352If your custom ``Field`` class deals with data structures that are more complex 
     353than strings, dates, integers or floats, then you'll need to override this 
     354method. As a general rule, the method should deal gracefully with any of the 
     355following 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 
     363In our ``HandField`` class, we're storing the data as a VARCHAR field in the 
     364database, so we need to be able to process strings and ``Hand`` instances in 
     365``to_python()``:: 
     366 
     367    import re 
    357368 
    358369    class HandField(models.Field): 
     
    363374                return value 
    364375 
    365             # The string case 
     376            # The string case. 
    366377            p1 = re.compile('.{26}') 
    367378            p2 = re.compile('..') 
     
    369380            return Hand(*args) 
    370381 
    371 Notice that we always return a ``Hand`` instance from this method. That is the 
    372 Python object we want to store in the model's attribute. 
     382Notice that we always return a ``Hand`` instance from this method. That's the 
     383Python object type we want to store in the model's attribute. 
    373384 
    374385``get_db_prep_save(self, value)`` 
     
    378389(as opposed to serialization). The ``value`` parameter is the current value of 
    379390the 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 a 
     391cannot retrieve the value itself), and the method should return data in a 
    381392format that can be used as a parameter in a query for the database backend. 
    382393 
     
    389400            return ''.join([''.join(l) for l in (self.north, 
    390401                    self.east, self.south, self.west)]) 
    391  
    392402 
    393403``pre_save(self, model_instance, add)`` 
     
    400410parameter will be ``True``, otherwise it will be ``False``. 
    401411 
    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
     412You only need to override this method if you want to preprocess the value 
     413somehow, just before saving. For example, Django's ``DateTimeField`` uses this 
     414method to set the attribute correctly in the case of ``auto_now`` or 
     415``auto_now_add``
    406416 
    407417If you do override this method, you must return the value of the attribute at 
     
    461471for the ``form_class`` argument and then delegate further handling to the 
    462472parent 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. Also 
    464 have a look at ``django.contrib.localflavor`` for some examples of custom 
    465 widgets. 
     473form widget). See the `forms documentation`_ for information about this, and 
     474take a look at the code in ``django.contrib.localflavor`` for some examples of 
     475custom widgets. 
    466476 
    467477Continuing our ongoing example, we can write the ``formfield()`` method as:: 
     
    472482        def formfield(self, **kwargs): 
    473483            # This is a fairly standard way to set up some defaults 
    474             # whilst letting the caller override them. 
     484            # while letting the caller override them. 
    475485            defaults = {'form_class': MyFormField} 
    476486            defaults.update(kwargs) 
    477487            return super(HandField, self).formfield(**defaults) 
    478488 
    479 This assumes we have some ``MyFormField`` field class (which has its own 
    480 default widget) imported. This document doesn't cover the details of writing 
    481 custom form fields. 
     489This assumes we're imported a ``MyFormField`` field class (which has its own 
     490default widget). This document doesn't cover the details of writing custom form 
     491fields. 
    482492 
    483493.. _helper functions: ../newforms/#generating-forms-for-models 
     
    491501simple cases. 
    492502 
    493 If you have created a ``db_type()`` method, you do not need to worry about 
     503If you have created a ``db_type()`` method, you don't need to worry about 
    494504``get_internal_type()`` -- it won't be used much. Sometimes, though, your 
    495505database storage is similar in type to some other field, so you can use that 
     
    513523``None``. See the documentation of ``db_type()`` above_ for reasons why this 
    514524might 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 the 
     525the serializer is a useful idea if you're ever going to be using the 
    516526serializer output in some other place, outside of Django. 
    517527 
     
    529539version of the data. This method has some internal uses that aren't of 
    530540interest to use here (mostly having to do with manipulators). For our 
    531 purposes, it is sufficient to return a one item dictionary that maps the 
     541purposes, it's sufficient to return a one item dictionary that maps the 
    532542attribute name to a string. 
    533543 
     
    550560-------------------- 
    551561 
    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  
     562Writing a custom field can be a tricky process, particularly if you're doing 
     563complex conversions between your Python types and your database and 
     564serialization formats. Here are a couple of tips to make things go more 
     565smoothly: 
     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  
    12781278 
    12791279If used with a numeric integer argument, ``floatformat`` rounds a number to 
    1280 that many decimal places. For example: 
     1280that many decimal places. For example: 
    12811281 
    12821282========  =========================  ======