Fixed #15308 -- Sphinx/reST fixes for the Custom Model Fields docs.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15547 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Gabriel Hurley 2011-02-16 00:24:49 +00:00
parent 9323f81dc0
commit a40685fdfc
1 changed files with 57 additions and 54 deletions

View File

@ -105,6 +105,8 @@ say, all the *north* cards first, then the *east*, *south* and *west* cards. So
What does a field class do? What does a field class do?
--------------------------- ---------------------------
.. class:: Field
All of Django's fields (and when we say *fields* in this document, we always All of Django's fields (and when we say *fields* in this document, we always
mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses
of :class:`django.db.models.Field`. Most of the information that Django records 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 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. 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 The :meth:`~django.db.models.Field.__init__` method takes the following
parameters: parameters:
@ -228,6 +232,8 @@ meaning they do for normal Django fields. See the :doc:`field documentation
The ``SubfieldBase`` metaclass The ``SubfieldBase`` metaclass
------------------------------ ------------------------------
.. class:: django.db.models.SubfieldBase
As we indicated in the introduction_, field subclasses are often needed for 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 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 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 little complex, but the code you need to write in your ``Field`` class is
simple: make sure your field subclass uses a special metaclass: simple: make sure your field subclass uses a special metaclass:
.. class:: django.db.models.SubfieldBase
For example:: For example::
class HandField(models.Field): class HandField(models.Field):
@ -255,13 +259,13 @@ For example::
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
# ... # ...
This ensures that the :meth:`to_python` method, documented below, will always be This ensures that the :meth:`.to_python` method, documented below, will always
called when the attribute is initialized. be called when the attribute is initialized.
ModelForms and custom fields 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 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, 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 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 custom field performs whatever input validation and data cleaning is
necessary to convert user-provided form input into a necessary to convert user-provided form input into a
`to_python()`-compatible model field value. This may require writing 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 your field to return a form field class whose `to_python()` returns the
correct datatype. correct datatype.
Documenting your custom field Documenting your custom field
----------------------------- -----------------------------
.. class:: django.db.models.Field .. attribute:: Field.description
.. attribute:: description
As always, you should document your field type, so users will know what it is. 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, 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 field type via the :doc:`django.contrib.admindocs
</ref/contrib/admin/admindocs>` application. To do this simply provide </ref/contrib/admin/admindocs>` application. To do this simply provide
descriptive text in a ``description`` class attribute of your custom field. In 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)'. application for a ``HandField`` will be 'A hand of cards (bridge style)'.
Useful methods Useful methods
@ -308,7 +310,7 @@ approximately decreasing order of importance, so start from the top.
Custom database types Custom database types
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
.. method:: db_type(self, connection) .. method:: Field.db_type(self, connection)
.. versionadded:: 1.2 .. versionadded:: 1.2
The ``connection`` argument was added to support multiple databases. 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. 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 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` field with Django by subclassing ``Field`` and implementing the
method, like so:: :meth:`.db_type` method, like so::
from django.db import models 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 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 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 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 ``datetime``. The simplest way to handle this in a :meth:`.db_type`
check the ``connection.settings_dict['ENGINE']`` attribute. method is to check the ``connection.settings_dict['ENGINE']`` attribute.
For example:: For example::
@ -349,11 +351,11 @@ For example::
else: else:
return 'timestamp' return 'timestamp'
The :meth:`db_type` method is only called by Django when the framework The :meth:`.db_type` method is only called by Django when the framework
constructs the ``CREATE TABLE`` statements for your application -- that is, when constructs the ``CREATE TABLE`` statements for your application -- that is,
you first create your tables. It's not called at any other time, so it can 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`` afford to execute slightly complex code, such as the
check in the above example. ``connection.settings_dict`` check in the above example.
Some database column types accept parameters, such as ``CHAR(25)``, where the Some database column types accept parameters, such as ``CHAR(25)``, where the
parameter ``25`` represents the maximum column length. In cases like these, 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) my_field = BetterCharField(25)
Finally, if your column requires truly complex SQL setup, return ``None`` from 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 :meth:`.db_type`. This will cause Django's SQL creation code to skip
field. You are then responsible for creating the column in the right table in over this field. You are then responsible for creating the column in the right
some other way, of course, but this gives you a way to tell Django to get out of table in some other way, of course, but this gives you a way to tell Django to
the way. get out of the way.
Converting database values to Python objects 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 Converts a value as returned by your database (or a serializer) to a Python
object. 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 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 database, so we need to be able to process strings and ``Hand`` instances in
:meth:`to_python`:: :meth:`.to_python`::
import re 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 **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`_ 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 Converting Python objects to query values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. method:: get_prep_value(self, value) .. method:: Field.get_prep_value(self, value)
.. versionadded:: 1.2 .. versionadded:: 1.2
This method was factored out of ``get_db_prep_value()`` 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`` database backends (as opposed to serialization). The ``value``
parameter is the current value of the model's attribute (a field has 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 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 This conversion should *not* include any database-specific
conversions. If database-specific conversions are required, they 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:: For example::
@ -475,43 +478,43 @@ For example::
Converting query values to database values 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 .. versionadded:: 1.2
The ``connection`` and ``prepared`` arguments were added to support multiple databases. The ``connection`` and ``prepared`` arguments were added to support multiple databases.
Some data types (for example, dates) need to be in a specific format Some data types (for example, dates) need to be in a specific format
before they can be used by a database backend. 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 be made. The specific connection that will be used for the query is
passed as the ``connection`` parameter. This allows you to use passed as the ``connection`` parameter. This allows you to use
backend-specific conversion logic if it is required. backend-specific conversion logic if it is required.
The ``prepared`` argument describes whether or not the value has 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 ``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 initial data conversions before performing any database-specific
processing. processing.
.. method:: get_db_prep_save(self, value, connection) .. method:: Field.get_db_prep_save(self, value, connection)
.. versionadded:: 1.2 .. versionadded:: 1.2
The ``connection`` argument was added to support multiple databases. The ``connection`` argument was added to support multiple databases.
Same as the above, but called when the Field value must be *saved* to Same as the above, but called when the Field value must be *saved* to
the database. As the default implementation just calls 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 unless your custom field needs a special conversion when being saved
that is not the same as the conversion used for normal query 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 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 value of the appropriate attribute from ``model_instance`` for this field.
The attribute name is in ``self.attname`` (this is set up by 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 :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 As with value conversions, preparing a value for database lookups is a
two phase process. two phase process.
.. method:: get_prep_lookup(self, lookup_type, value) .. method:: Field.get_prep_lookup(self, lookup_type, value)
.. versionadded:: 1.2 .. versionadded:: 1.2
This method was factored out of ``get_db_prep_lookup()`` 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 performing generic data validity checks
Prepares the ``value`` for passing to the database when used in a lookup (a 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 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 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 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 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 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: else:
raise TypeError('Lookup type %r not supported.' % lookup_type) 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 .. versionadded:: 1.2
The ``connection`` and ``prepared`` arguments were added to support multiple databases. The ``connection`` and ``prepared`` arguments were added to support multiple databases.
Performs any database-specific data conversions required by a lookup. 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. be used for the query is passed as the ``connection`` parameter.
The ``prepared`` argument describes whether the value has already been 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 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. 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. 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
</topics/forms/index>` for information about this, and take a look at the code in </topics/forms/index>` for information about this, and take a look at the code in
:mod:`django.contrib.localflavor` for some examples of custom widgets. :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): class HandField(models.Field):
# ... # ...
@ -635,14 +638,14 @@ fields.
Emulating built-in field types 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` 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 subclass we are emulating at the database level. This is used to determine the
type of database column for simple cases. type of database column for simple cases.
If you have created a :meth:`db_type` method, you don't need to worry about 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 :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 database storage is similar in type to some other field, so you can use that
other field's logic to create the right column. 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`` 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. 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 the database backend you are using -- that is, it doesn't appear in
``django.db.backends.<db_name>.creation.DATA_TYPES`` -- the string will still be ``django.db.backends.<db_name>.creation.DATA_TYPES`` -- the string will still be
used by the serializer, but the default :meth:`db_type` method will return 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 ``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 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 serializer is a useful idea if you're ever going to be using the serializer
output in some other place, outside of Django. 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 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 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 output. Calling :meth:`Field._get_val_from_obj(obj)` is the best way to get the