diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt index 7dbbf93d1f..5753abd56b 100644 --- a/docs/howto/custom-model-fields.txt +++ b/docs/howto/custom-model-fields.txt @@ -105,6 +105,8 @@ say, all the *north* cards first, then the *east*, *south* and *west* cards. So What does a field class do? --------------------------- +.. class:: Field + All of Django's fields (and when we say *fields* in this document, we always mean model fields and not :doc:`form fields `) are subclasses of :class:`django.db.models.Field`. Most of the information that Django records @@ -190,6 +192,8 @@ card values plus their suits; 104 characters in total. you want your fields to be more strict about the options they select, or to use the simpler, more permissive behavior of the current fields. +.. method:: Field.__init__ + The :meth:`~django.db.models.Field.__init__` method takes the following parameters: @@ -228,6 +232,8 @@ meaning they do for normal Django fields. See the :doc:`field documentation The ``SubfieldBase`` metaclass ------------------------------ +.. class:: django.db.models.SubfieldBase + As we indicated in the introduction_, field subclasses are often needed for two reasons: either to take advantage of a custom database column type, or to handle complex Python types. Obviously, a combination of the two is also @@ -242,8 +248,6 @@ appropriate Python object. The details of how this happens internally are a little complex, but the code you need to write in your ``Field`` class is simple: make sure your field subclass uses a special metaclass: -.. class:: django.db.models.SubfieldBase - For example:: class HandField(models.Field): @@ -255,13 +259,13 @@ For example:: def __init__(self, *args, **kwargs): # ... -This ensures that the :meth:`to_python` method, documented below, will always be -called when the attribute is initialized. +This ensures that the :meth:`.to_python` method, documented below, will always +be called when the attribute is initialized. ModelForms and custom fields ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -If you use :class:`~django.db.models.SubfieldBase`, :meth:`to_python` +If you use :class:`~django.db.models.SubfieldBase`, :meth:`.to_python` will be called every time an instance of the field is assigned a value. This means that whenever a value may be assigned to the field, you need to ensure that it will be of the correct datatype, or that @@ -277,16 +281,14 @@ Therefore, you must ensure that the form field used to represent your custom field performs whatever input validation and data cleaning is necessary to convert user-provided form input into a `to_python()`-compatible model field value. This may require writing a -custom form field, and/or implementing the :meth:`formfield` method on +custom form field, and/or implementing the :meth:`.formfield` method on your field to return a form field class whose `to_python()` returns the correct datatype. Documenting your custom field ----------------------------- -.. class:: django.db.models.Field - -.. attribute:: description +.. attribute:: Field.description As always, you should document your field type, so users will know what it is. In addition to providing a docstring for it, which is useful for developers, @@ -294,7 +296,7 @@ you can also allow users of the admin app to see a short description of the field type via the :doc:`django.contrib.admindocs ` application. To do this simply provide descriptive text in a ``description`` class attribute of your custom field. In -the above example, the type description displayed by the ``admindocs`` +the above example, the description displayed by the ``admindocs`` application for a ``HandField`` will be 'A hand of cards (bridge style)'. Useful methods @@ -308,7 +310,7 @@ approximately decreasing order of importance, so start from the top. Custom database types ~~~~~~~~~~~~~~~~~~~~~ -.. method:: db_type(self, connection) +.. method:: Field.db_type(self, connection) .. versionadded:: 1.2 The ``connection`` argument was added to support multiple databases. @@ -317,8 +319,8 @@ Returns the database column data type for the :class:`~django.db.models.Field`, taking into account the connection object, and the settings associated with it. Say you've created a PostgreSQL custom type called ``mytype``. You can use this -field with Django by subclassing ``Field`` and implementing the :meth:`db_type` -method, like so:: +field with Django by subclassing ``Field`` and implementing the +:meth:`.db_type` method, like so:: from django.db import models @@ -337,8 +339,8 @@ Once you have ``MytypeField``, you can use it in any model, just like any other If you aim to build a database-agnostic application, you should account for differences in database column types. For example, the date/time column type in PostgreSQL is called ``timestamp``, while the same column in MySQL is called -``datetime``. The simplest way to handle this in a ``db_type()`` method is to -check the ``connection.settings_dict['ENGINE']`` attribute. +``datetime``. The simplest way to handle this in a :meth:`.db_type` +method is to check the ``connection.settings_dict['ENGINE']`` attribute. For example:: @@ -349,11 +351,11 @@ For example:: else: return 'timestamp' -The :meth:`db_type` method is only called by Django when the framework -constructs the ``CREATE TABLE`` statements for your application -- that is, when -you first create your tables. It's not called at any other time, so it can -afford to execute slightly complex code, such as the ``connection.settings_dict`` -check in the above example. +The :meth:`.db_type` method is only called by Django when the framework +constructs the ``CREATE TABLE`` statements for your application -- that is, +when you first create your tables. It's not called at any other time, so it can +afford to execute slightly complex code, such as the +``connection.settings_dict`` check in the above example. Some database column types accept parameters, such as ``CHAR(25)``, where the parameter ``25`` represents the maximum column length. In cases like these, @@ -390,15 +392,15 @@ time -- i.e., when the class is instantiated. To do that, just implement my_field = BetterCharField(25) Finally, if your column requires truly complex SQL setup, return ``None`` from -:meth:`db_type`. This will cause Django's SQL creation code to skip over this -field. You are then responsible for creating the column in the right table in -some other way, of course, but this gives you a way to tell Django to get out of -the way. +:meth:`.db_type`. This will cause Django's SQL creation code to skip +over this field. You are then responsible for creating the column in the right +table in some other way, of course, but this gives you a way to tell Django to +get out of the way. Converting database values to Python objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: to_python(self, value) +.. method:: Field.to_python(self, value) Converts a value as returned by your database (or a serializer) to a Python object. @@ -420,7 +422,7 @@ with any of the following arguments: In our ``HandField`` class, we're storing the data as a VARCHAR field in the database, so we need to be able to process strings and ``Hand`` instances in -:meth:`to_python`:: +:meth:`.to_python`:: import re @@ -442,17 +444,18 @@ Python object type we want to store in the model's attribute. **Remember:** If your custom field needs the :meth:`to_python` method to be called when it is created, you should be using `The SubfieldBase metaclass`_ -mentioned earlier. Otherwise :meth:`to_python` won't be called automatically. +mentioned earlier. Otherwise :meth:`.to_python` won't be called +automatically. Converting Python objects to query values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: get_prep_value(self, value) +.. method:: Field.get_prep_value(self, value) .. versionadded:: 1.2 This method was factored out of ``get_db_prep_value()`` -This is the reverse of :meth:`to_python` when working with the +This is the reverse of :meth:`.to_python` when working with the database backends (as opposed to serialization). The ``value`` parameter is the current value of the model's attribute (a field has no reference to its containing model, so it cannot retrieve the value @@ -461,7 +464,7 @@ prepared for use as a parameter in a query. This conversion should *not* include any database-specific conversions. If database-specific conversions are required, they -should be made in the call to :meth:`get_db_prep_value`. +should be made in the call to :meth:`.get_db_prep_value`. For example:: @@ -475,43 +478,43 @@ For example:: Converting query values to database values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: get_db_prep_value(self, value, connection, prepared=False) +.. method:: Field.get_db_prep_value(self, value, connection, prepared=False) .. versionadded:: 1.2 The ``connection`` and ``prepared`` arguments were added to support multiple databases. Some data types (for example, dates) need to be in a specific format before they can be used by a database backend. -:meth:`get_db_prep_value` is the method where those conversions should +:meth:`.get_db_prep_value` is the method where those conversions should be made. The specific connection that will be used for the query is passed as the ``connection`` parameter. This allows you to use backend-specific conversion logic if it is required. The ``prepared`` argument describes whether or not the value has -already been passed through :meth:`get_prep_value` conversions. When +already been passed through :meth:`.get_prep_value` conversions. When ``prepared`` is False, the default implementation of -:meth:`get_db_prep_value` will call :meth:`get_prep_value` to do +:meth:`.get_db_prep_value` will call :meth:`.get_prep_value` to do initial data conversions before performing any database-specific processing. -.. method:: get_db_prep_save(self, value, connection) +.. method:: Field.get_db_prep_save(self, value, connection) .. versionadded:: 1.2 The ``connection`` argument was added to support multiple databases. Same as the above, but called when the Field value must be *saved* to the database. As the default implementation just calls -``get_db_prep_value``, you shouldn't need to implement this method +:meth:`.get_db_prep_value`, you shouldn't need to implement this method unless your custom field needs a special conversion when being saved that is not the same as the conversion used for normal query -parameters (which is implemented by ``get_db_prep_value``). +parameters (which is implemented by :meth:`.get_db_prep_value`). Preprocessing values before saving ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: pre_save(self, model_instance, add) +.. method:: Field.pre_save(self, model_instance, add) -This method is called just prior to :meth:`get_db_prep_save` and should return +This method is called just prior to :meth:`.get_db_prep_save` and should return the value of the appropriate attribute from ``model_instance`` for this field. The attribute name is in ``self.attname`` (this is set up by :class:`~django.db.models.Field`). If the model is being saved to the database @@ -535,12 +538,12 @@ Preparing values for use in database lookups As with value conversions, preparing a value for database lookups is a two phase process. -.. method:: get_prep_lookup(self, lookup_type, value) +.. method:: Field.get_prep_lookup(self, lookup_type, value) .. versionadded:: 1.2 This method was factored out of ``get_db_prep_lookup()`` -:meth:`get_prep_lookup` performs the first phase of lookup preparation, +:meth:`.get_prep_lookup` performs the first phase of lookup preparation, performing generic data validity checks Prepares the ``value`` for passing to the database when used in a lookup (a @@ -555,7 +558,7 @@ should raise either a ``ValueError`` if the ``value`` is of the wrong sort (a list when you were expecting an object, for example) or a ``TypeError`` if your field does not support that type of lookup. For many fields, you can get by with handling the lookup types that need special handling for your field -and pass the rest to the :meth:`get_db_prep_lookup` method of the parent class. +and pass the rest to the :meth:`.get_db_prep_lookup` method of the parent class. If you needed to implement ``get_db_prep_save()``, you will usually need to implement ``get_prep_lookup()``. If you don't, ``get_prep_value`` will be @@ -586,21 +589,21 @@ accepted lookup types to ``exact`` and ``in``:: else: raise TypeError('Lookup type %r not supported.' % lookup_type) -.. method:: get_db_prep_lookup(self, lookup_type, value, connection, prepared=False) +.. method:: Field.get_db_prep_lookup(self, lookup_type, value, connection, prepared=False) .. versionadded:: 1.2 The ``connection`` and ``prepared`` arguments were added to support multiple databases. Performs any database-specific data conversions required by a lookup. -As with :meth:`get_db_prep_value`, the specific connection that will +As with :meth:`.get_db_prep_value`, the specific connection that will be used for the query is passed as the ``connection`` parameter. The ``prepared`` argument describes whether the value has already been -prepared with :meth:`get_prep_lookup`. +prepared with :meth:`.get_prep_lookup`. Specifying the form field for a model field ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: formfield(self, form_class=forms.CharField, **kwargs) +.. method:: Field.formfield(self, form_class=forms.CharField, **kwargs) Returns the default form field to use when this field is displayed in a model. This method is called by the :class:`~django.forms.ModelForm` helper. @@ -613,7 +616,7 @@ field (and even a form widget). See the :doc:`forms documentation ` for information about this, and take a look at the code in :mod:`django.contrib.localflavor` for some examples of custom widgets. -Continuing our ongoing example, we can write the :meth:`formfield` method as:: +Continuing our ongoing example, we can write the :meth:`.formfield` method as:: class HandField(models.Field): # ... @@ -635,14 +638,14 @@ fields. Emulating built-in field types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: get_internal_type(self) +.. method:: Field.get_internal_type(self) Returns a string giving the name of the :class:`~django.db.models.Field` subclass we are emulating at the database level. This is used to determine the type of database column for simple cases. -If you have created a :meth:`db_type` method, you don't need to worry about -:meth:`get_internal_type` -- it won't be used much. Sometimes, though, your +If you have created a :meth:`.db_type` method, you don't need to worry about +:meth:`.get_internal_type` -- it won't be used much. Sometimes, though, your database storage is similar in type to some other field, so you can use that other field's logic to create the right column. @@ -657,11 +660,11 @@ For example:: No matter which database backend we are using, this will mean that ``syncdb`` and other SQL commands create the right column type for storing a string. -If :meth:`get_internal_type` returns a string that is not known to Django for +If :meth:`.get_internal_type` returns a string that is not known to Django for the database backend you are using -- that is, it doesn't appear in ``django.db.backends..creation.DATA_TYPES`` -- the string will still be -used by the serializer, but the default :meth:`db_type` method will return -``None``. See the documentation of :meth:`db_type` for reasons why this might be +used by the serializer, but the default :meth:`.db_type` method will return +``None``. See the documentation of :meth:`.db_type` for reasons why this might be useful. Putting a descriptive string in as the type of the field for the serializer is a useful idea if you're ever going to be using the serializer output in some other place, outside of Django. @@ -669,7 +672,7 @@ output in some other place, outside of Django. Converting field data for serialization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: value_to_string(self, obj) +.. method:: Field.value_to_string(self, obj) This method is used by the serializers to convert the field into a string for output. Calling :meth:`Field._get_val_from_obj(obj)` is the best way to get the