Copy-edited model-API docs

git-svn-id: http://code.djangoproject.com/svn/django/trunk@136 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2005-07-17 04:20:57 +00:00
parent d0e5eab657
commit 5e309eb6e4
1 changed files with 390 additions and 377 deletions

View File

@ -3,14 +3,14 @@ Model reference
=============== ===============
Django's models are the bread and butter of the framework. There's a huge Django's models are the bread and butter of the framework. There's a huge
array of options available to you when defining your data models; this array of options available to you when defining your data models. This
document explains all of them. document explains them.
Options for models Options for models
================== ==================
A list of all possible options for a model object follows. Although there's a A list of all possible options for a model object follows. Although there's a
wide array of possible options, only ``fields`` is required. wide array of options, only ``fields`` is required.
``admin`` ``admin``
A ``meta.Admin`` object; see `Admin options`_. If this field isn't given, A ``meta.Admin`` object; see `Admin options`_. If this field isn't given,
@ -21,7 +21,7 @@ wide array of possible options, only ``fields`` is required.
db_table = "pizza_orders" db_table = "pizza_orders"
If not given, this will use ``app_label + '_' + module_name``. If this isn't given, Django will use ``app_label + '_' + module_name``.
``exceptions`` ``exceptions``
Names of extra exception subclasses to include in the generated module. Names of extra exception subclasses to include in the generated module.
@ -31,7 +31,7 @@ wide array of possible options, only ``fields`` is required.
exceptions = ("DisgustingToppingsException", "BurntCrust") exceptions = ("DisgustingToppingsException", "BurntCrust")
``fields`` ``fields``
A list of field objects; see `Field objects`_. For example:: A list of field objects. See `Field objects`_. For example::
fields = ( fields = (
meta.CharField('customer_name', 'customer name', maxlength=15), meta.CharField('customer_name', 'customer name', maxlength=15),
@ -41,14 +41,14 @@ wide array of possible options, only ``fields`` is required.
) )
``get_latest_by`` ``get_latest_by``
The name of a date or datetime field; if given, the module will have a The name of a ``DateField`` or ``DateTimeField``; if given, the module will
``get_latest()`` function which fetches the "latest" object in terms of have a ``get_latest()`` function that fetches the "latest" object according
that field:: to that field::
get_latest_by = "order_date" get_latest_by = "order_date"
``module_constants`` ``module_constants``
A dict of name/values to use as extra module-level constants:: A dictionary of names/values to use as extra module-level constants::
module_constants = { module_constants = {
'MEAT_TYPE_PEPPERONI' : 1, 'MEAT_TYPE_PEPPERONI' : 1,
@ -60,7 +60,8 @@ wide array of possible options, only ``fields`` is required.
module_name = "pizza_orders" module_name = "pizza_orders"
If not given this will use a lowercased version of the class name. If this isn't given, Django will use a lowercased version of the class
name, plus "s".
``order_with_respect_to`` ``order_with_respect_to``
Marks this object as "orderable" with respect to the given field. This is Marks this object as "orderable" with respect to the given field. This is
@ -73,20 +74,20 @@ wide array of possible options, only ``fields`` is required.
to allow the toppings to be ordered with respect to the associated pizza. to allow the toppings to be ordered with respect to the associated pizza.
``ordering`` ``ordering``
The default ordering for tho object:: The default ordering for the object, for use by ``get_list`` and the admin::
ordering = (('order_date', 'DESC'),) ordering = (('order_date', 'DESC'),)
This is a tuple of 2-tuples; each 2-tuple is ``(field_name, ordering_type)`` This is a tuple of 2-tuples. Each 2-tuple is ``(field_name, ordering_type)``
where ordering_type is either ``"ASC"`` or ``"DESC"``. You may also use the where ordering_type is either ``"ASC"`` or ``"DESC"``. You can also use the
magic ``(None, "RANDOM")`` ordering tuple for random ordering. ``(None, "RANDOM")`` for random ordering.
``permissions`` ``permissions``
Extra permissions to enter into the permissions table when creating this Extra permissions to enter into the permissions table when creating this
object. A add, delete, and change permission is automatically created for object. A add, delete, and change permission is automatically created for
each object; this option specifies extra permissions:: each object. This option specifies extra permissions::
permissions = (("may_delivier_pizzas", "Can deliver pizzas"),) permissions = (("can_delivier_pizzas", "Can deliver pizzas"),)
This is a list of 2-tuples of This is a list of 2-tuples of
``(permission_code, human_readable_permission_name)``. ``(permission_code, human_readable_permission_name)``.
@ -97,14 +98,14 @@ wide array of possible options, only ``fields`` is required.
unique_together = (("driver_id", "restaurant_id"),) unique_together = (("driver_id", "restaurant_id"),)
This is a list of lists of fields that must be unique when considered This is a list of lists of fields that must be unique when considered
together. together. It's used in the Django admin.
``verbose_name`` ``verbose_name``
A human-readable name for the object, singular:: A human-readable name for the object, singular::
verbose_name = "pizza" verbose_name = "pizza"
If not given, this will use a munged version of the class name: If this isn't given, Django will use a munged version of the class name:
``CamelCase`` becomes ``camel case``. ``CamelCase`` becomes ``camel case``.
``verbose_name_plural`` ``verbose_name_plural``
@ -112,13 +113,13 @@ wide array of possible options, only ``fields`` is required.
verbose_name_plural = "stories" verbose_name_plural = "stories"
If not given, ``verbose_name + "s"`` will automatically be used. If this isn't given, Django will use ``verbose_name + "s"``.
Field objects Field objects
============= =============
The list of fields is the most important part of a data model. Each item in The list of fields is the most important part of a data model. Each item in
the ``fields`` list is an instance of a ``meta.Field`` subclass, and maps to the ``fields`` list is an instance of a ``meta.Field`` subclass and maps to
a database field. a database field.
All field objects -- except for ``ForeignKey`` and ``ManyToManyField`` (see All field objects -- except for ``ForeignKey`` and ``ManyToManyField`` (see
@ -130,8 +131,8 @@ contain spaces, punctuation, etc.
General field options General field options
--------------------- ---------------------
Each type of field takes a different set of options, but there are some Each type of field takes a different set of options, but some options are
options that are common to all field types. These options are: common to all field types. These options are:
====================== =================================================== ====================== ===================================================
Option Description Option Description
@ -139,14 +140,15 @@ options that are common to all field types. These options are:
``blank`` If ``True``, the field is allowed to be blank. ``blank`` If ``True``, the field is allowed to be blank.
Note that this is different from ``null`` in that Note that this is different from ``null`` in that
string fields will store the empty string instead of string fields will store the empty string instead of
``NULL`` internally; this means that to create a ``NULL`` internally. This means that to create a
field that stores nulls you must pass ``blank=True`` field that stores nulls you must pass ``blank=True``
and ``null=True``. and ``null=True``.
``choices`` A list of 2-tuples to use as choices for this ``choices`` A list of 2-tuples to use as choices for this
field.If this is given, instead of the standard field. If this is given, Django's admin will use a
field a option menu will be used, limiting choices select box instead of the standard text field and
to the choices given. A choices list looks like:: will limit choices to the choices given. A choices
list looks like::
YEAR_IN_SCHOOL_CHOICES = ( YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'), ('FR', 'Freshman'),
@ -157,8 +159,8 @@ options that are common to all field types. These options are:
) )
The first element in each tuple is the actual value The first element in each tuple is the actual value
to be stored; the second element is the human to be stored. The second element is the
readable name for the option. human-readable name for the option.
``core`` For objects that are edited inline to a related ``core`` For objects that are edited inline to a related
object. If all "core" fields in an inline-edited object. If all "core" fields in an inline-edited
@ -173,35 +175,37 @@ options that are common to all field types. These options are:
``default`` The default value for the field. ``default`` The default value for the field.
``editable`` ``True`` by default, if set to ``False`` the field ``editable`` ``True`` by default. If this is set to ``False``,
will not be editable in the admin. the field will not be editable in the admin.
``help_text`` Extra "help" text to be displayed with the field. ``help_text`` Extra "help" text to be displayed under the field
on the object's admin form.
``null`` If ``True`` empty values in the field will be ``null`` If ``True``, empty values in the field will be
stored as ``NULL`` in the database. stored as ``NULL`` in the database.
``primary_key`` If ``True`` this field is the primary key for the ``primary_key`` If ``True``, this field is the primary key for the
table. You only need to use this if you don't want table. You only need to use this if you don't want
the standard "id" field created and used as the the standard "id" field created and used as the
primary key. primary key.
Implies ``blank=False``, ``null=False``, and Implies ``blank=False``, ``null=False``, and
``unique=True``. Only one primary key is allowed ``unique=True``. Only one primary key is allowed
on each object. on an object.
``radio_admin`` If ``choices`` is given, or if the field is a ``radio_admin`` If ``choices`` is given, or if the field is a
ManyToOne relation, use a radio button interface ManyToOne relation, use a radio-button interface
for the choices instead of the standard options for the choices instead of the standard select-box
menu interface. interface.
``unique`` If ``True`` this field must be unique throughout ``unique`` If ``True``, this field must be unique throughout
the table. the table. This is enforced at the database level
and at the Django admin-form level.
``unique_for_date`` Set this to the name of a ``DateField`` or ``unique_for_date`` Set this to the name of a ``DateField`` or
``DateTimeField`` to require that this field ``DateTimeField`` to require that this field
be unique for the value of the date field. That be unique for the value of the date field. For
is, if you have a field, ``title`` that has example, if you have a field ``title`` that has
``unique_for_date="pub_date"``, then it is an ``unique_for_date="pub_date"``, then it is an
error to have two rows with the same ``title`` error to have two rows with the same ``title``
and the same ``pub_date``. and the same ``pub_date``.
@ -209,23 +213,18 @@ options that are common to all field types. These options are:
``unique_for_month`` Like ``unique_for_date``, but requires the field ``unique_for_month`` Like ``unique_for_date``, but requires the field
to be unique with respect to the month. to be unique with respect to the month.
``unique_for_year`` Like ``unique_for_date`` and ``unique_for_month`` ``unique_for_year`` Like ``unique_for_date`` and ``unique_for_month``.
but, well, you get the idea.
``validator_list`` A list of extra validators to apply to the field. ``validator_list`` A list of extra validators to apply to the field.
See the `Form fields guide`_ for information about
validators.
====================== =================================================== ====================== ===================================================
.. _`Form fields guide`: http://www.djangoproject.com/FIXME/
Field Types Field Types
----------- -----------
``AutoField`` ``AutoField``
An ``IntegerField`` that automatically increments. You usually won't need to An ``IntegerField`` that automatically increments. You usually won't need to
use this directly; a primary key field will automatically be added to your use this directly; a primary key field will automatically be added to your
model if you don't specify otherwise. That automatically added field is:: model if you don't specify otherwise. That automatically-added field is::
meta.AutoField('id', 'ID', primary_key=True) meta.AutoField('id', 'ID', primary_key=True)
@ -234,16 +233,17 @@ Field Types
``CharField`` ``CharField``
A text field. These are displayed in the admin as single-line text inputs, so A text field. These are displayed in the admin as single-line text inputs, so
for large amounts of text use a ``TextField``. for large amounts of text, use a ``TextField``.
``CharField``s have an extra required argument: ``maxlength``; the maximum ``CharField``s have an extra required argument: ``maxlength``, the maximum
length (in characters) of the field. length (in characters) of the field. The maxlength is enforced at the database
level and in Django's admin validation.
``CommaSeparatedIntegerField`` ``CommaSeparatedIntegerField``
A field of integers separated by commas. A field of integers separated by commas.
``DateField`` ``DateField``
A, um, date field. Has a few extra optional options: A date field. Has a few extra optional options:
====================== =================================================== ====================== ===================================================
Option Description Option Description
@ -253,22 +253,23 @@ Field Types
timestamps. timestamps.
``auto_now_add`` Automatically set the field to now when the object ``auto_now_add`` Automatically set the field to now when the object
is first created. Useful for creation timestamps. is first created. Useful for creation of
timestamps.
====================== =================================================== ====================== ===================================================
``DateTimeField`` ``DateTimeField``
A date and time field. Takes the same extra options as ``DateField``. A date and time field. Takes the same extra options as ``DateField``.
``EmailField`` ``EmailField``
A ``CharField`` that checks that the value is a valid email address. Because A ``CharField`` that checks that the value is a valid e-mail address.
validating email addresses can be tricky, this is a pretty loose test. Because validating e-mail addresses can be tricky, this is a pretty loose
test.
``FileField`` ``FileField``
A file-upload field. Takes on additional option, ``upload_to`` which is A file-upload field. Takes an additional option, ``upload_to``, which is
a path to upload the file to. This path may contain `strftime formatting`_ a local filesystem path to upload the file to. This path may contain
which will be replaced by the date/time of the file upload (so that uploaded `strftime formatting`_, which will be replaced by the date/time of the file
files don't fill up the given directory). upload (so that uploaded files don't fill up the given directory).
.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941 .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
@ -312,16 +313,16 @@ Field Types
interface. interface.
``edit_inline_type`` This is either ``meta.TABULAR`` or ``edit_inline_type`` This is either ``meta.TABULAR`` or
``meta.STACKED`` and controls weather the inline ``meta.STACKED`` and controls whether the inline
editable objects are displayed as a table or as editable objects are displayed as a table or as
a "stack" of fieldsets. Defaults to a "stack" of fieldsets. Defaults to
``meta.STACKED``. ``meta.STACKED``.
``limit_choices_to`` A dictionary of lookup arguments and values (see ``limit_choices_to`` A dictionary of lookup arguments and values (see
the `Database API reference`_) to limit choices the `Database API reference`_) that limit the
of this object to. Use this along with available admin choices for this object. Use this
``meta.LazyDate`` to limit choices of objects with ``meta.LazyDate`` to limit choices of objects
by date, for example:: by date. For example::
limit_choices_to = {'pub_date__lte' : meta.LazyDate()} limit_choices_to = {'pub_date__lte' : meta.LazyDate()}
@ -338,18 +339,19 @@ Field Types
that a user never enters more than 10 toppings. that a user never enters more than 10 toppings.
Note that this doesn't ensure more than 10 related Note that this doesn't ensure more than 10 related
toppings ever get created. toppings ever get created. It just controls the
interface.
``min_num_in_admin`` The minimum number of related objects displayed in ``min_num_in_admin`` The minimum number of related objects displayed in
the admin. Normally, at the creation stage the admin. Normally, at the creation stage,
``num_in_admin`` inline objects are shown, and at ``num_in_admin`` inline objects are shown, and at
the edit stage ``num_extra_on_change`` objects are the edit stage ``num_extra_on_change`` blank
shown in addition to all pre-existing related objects are shown in addition to all pre-existing
objects. However, no fewer than related objects. However, no fewer than
``min_num_in_admin`` related objects will ever be ``min_num_in_admin`` related objects will ever be
displayed. displayed.
``num_extra_on_change`` The number of extra blank related object fields to ``num_extra_on_change`` The number of extra blank related-object fields to
show at the change stage. show at the change stage.
``num_in_admin`` The default number of inline objects to display ``num_in_admin`` The default number of inline objects to display
@ -358,14 +360,14 @@ Field Types
``raw_id_admin`` Only display a field for the integer to be entered ``raw_id_admin`` Only display a field for the integer to be entered
instead of a drop-down menu. This is useful when instead of a drop-down menu. This is useful when
related to an object type that will have too many related to an object type that will have too many
rows to make a menu practical. rows to make a select box practical.
Not used with ``edit_inline``. Not used with ``edit_inline``.
``rel_name`` The name of the relation. In the above example, ``rel_name`` The name of the relation. In the above example,
this would default to 'pizza' (so that the this would default to 'pizza' (so that the
``Toppings`` object would have a ``get_pizza()`` ``Toppings`` object would have a ``get_pizza()``
function; if you set ``rel_name`` to "pie", then function. If you set ``rel_name`` to "pie", then
the function would be called ``get_pie()`` and the the function would be called ``get_pie()`` and the
field name would be ``pie_id``. field name would be ``pie_id``.
@ -411,7 +413,7 @@ Field Types
``to_field`` The field on the related object that the relation ``to_field`` The field on the related object that the relation
is to. This is almost always ``id``, but if the is to. This is almost always ``id``, but if the
PK on the other object is named something primary key on the other object is named something
different, this is how to indicate that. different, this is how to indicate that.
======================= ============================================================ ======================= ============================================================
@ -422,8 +424,12 @@ Field Types
image. Has two extra optional arguments, ``height_field`` and ``width_field`` image. Has two extra optional arguments, ``height_field`` and ``width_field``
which, if set, will be auto-populated with the height and width of the image. which, if set, will be auto-populated with the height and width of the image.
Requires the `Python Imaging Library`_.
.. _Python Imaging Library: http://www.pythonware.com/products/pil/
``IntegerField`` ``IntegerField``
An integer, surprisingly. An integer.
``IPAddressField`` ``IPAddressField``
An IP address, in string format (i.e. "24.124.1.30"). An IP address, in string format (i.e. "24.124.1.30").
@ -439,9 +445,9 @@ Field Types
) )
Many-to-many relations are a bit different from other fields. First, they Many-to-many relations are a bit different from other fields. First, they
aren't actually a field per se since they use a intermediary join table. aren't actually a field per se, because they use a intermediary join table.
Second, they don't take any of the same options as the rest of the fields, Second, they don't take any of the same options as the rest of the fields.
the only options taken are: The only options taken are:
======================= ============================================================ ======================= ============================================================
Option Description Option Description
@ -450,9 +456,10 @@ Field Types
``ManyToOneField``, above. ``ManyToOneField``, above.
``filter_interface`` Use a nifty unobtrusive Javascript "filter" interface ``filter_interface`` Use a nifty unobtrusive Javascript "filter" interface
instead of the usability-challenged ``<select multiple>``. instead of the usability-challenged ``<select multiple>``
The value should be ``meta.HORIZONTAL`` or ``meta.VERTICAL`` in the admin form for this object. The value should be
(i.e. should the interface be stacked horizontally or ``meta.HORIZONTAL`` or ``meta.VERTICAL`` (i.e.
should the interface be stacked horizontally or
vertically). vertically).
``limit_choices_to`` See the description under ``ManyToOneField``, above. ``limit_choices_to`` See the description under ``ManyToOneField``, above.
@ -490,19 +497,22 @@ Field Types
Like an ``IntegerField``, but must be positive. Like an ``IntegerField``, but must be positive.
``PositiveSmallIntegerField`` ``PositiveSmallIntegerField``
Like a ``PositiveIntegerField``, but only allows values below 32767. Like a ``PositiveIntegerField``, but only allows values under a certain
(database-dependent) point.
``SlugField`` ``SlugField``
A "slug" suitable for parts of a URL; only allows alpha-numeric characters and A "slug," suitable for parts of a URL. Only allows alphanumeric characters
underscores. and underscores.
Implies ``maxlength=50`` and ``db_index=True``. Implies ``maxlength=50`` and ``db_index=True``.
Accepts an extra option, ``prepopulate_from`` which is a list of fields from Accepts an extra option, ``prepopulate_from``, which is a list of fields
which to auto-populate the slug. from which to auto-populate the slug, via JavaScript, in the object's admin
form.
``SmallIntegerField`` ``SmallIntegerField``
Like an ``IntegerField``, but must be between -32768 and 32767. Like an ``IntegerField``, but only allows values under a certain
(database-dependent) point.
``TextField`` ``TextField``
A large text field (``<textarea>`` in HTML). A large text field (``<textarea>`` in HTML).
@ -512,16 +522,17 @@ Field Types
``DateTimeField``. ``DateTimeField``.
``URLField`` ``URLField``
A field for a URL. If the ``verify_exists`` option is ``True``, the URL given A field for a URL. If the ``verify_exists`` option is ``True`` (default),
will be checked for existence (i.e. actually loads and doesn't give a 404 the URL given will be checked for existence (i.e., the URL actually loads
response). and doesn't give a 404 response).
``USStateField`` ``USStateField``
A US state. A two-letter U.S. state abbreviation.
``XMLField`` ``XMLField``
A field containing XML. Takes one required argument, ``schema_path`` which A field containing XML. Takes one required argument, ``schema_path``, which
is the path to a RelaxNG_ scheme against which to validate the field. is the filesystem path to a RelaxNG_ schema against which to validate the
field.
.. _RelaxNG: http://www.relaxng.org/ .. _RelaxNG: http://www.relaxng.org/
@ -553,14 +564,14 @@ object, which has the following options (of which only ``fields`` is required):
``classes`` ``classes``
Extra CSS classes to apply to the fieldset. This is a simple Extra CSS classes to apply to the fieldset. This is a simple
string; you can apply multiple classes by separating them with string. You can apply multiple classes by separating them with
spaces. spaces.
Two useful classes defined by the default stylesheet are ``collapse`` Two useful classes defined by the default stylesheet are
and ``wide``. Fieldsets with the ``collapse`` style will be ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
initially collapsed in the admin and replaced with a small "click will be initially collapsed in the admin and replaced with a small
to expand" link. Fieldsets with the ``wide`` style will be given "click to expand" link. Fieldsets with the ``wide`` style will be
extra horizontal space. given extra horizontal space.
For example (taken from the ``core.flatfiles`` model):: For example (taken from the ``core.flatfiles`` model)::
@ -579,9 +590,9 @@ object, which has the following options (of which only ``fields`` is required):
.. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png .. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png
``js`` ``js``
Extra JavaScript files to link into the admin screen. This can be used to A list of strings representing URLs of JavaScript files to link into the
tweak a given type of admin page in JS or to provide "quick links" to fill admin screen. This can be used to tweak a given type of admin page in JS or
in default values for certain fields. to provide "quick links" to fill in default values for certain fields.
``list_display`` ``list_display``
List of fields to display on the list page in the admin. List of fields to display on the list page in the admin.
@ -595,24 +606,24 @@ object, which has the following options (of which only ``fields`` is required):
* If the field is a ``BooleanField``, a "on" or "off" icon will * If the field is a ``BooleanField``, a "on" or "off" icon will
be displayed instead of ``True`` or ``False``. be displayed instead of ``True`` or ``False``.
* If the field name given does not exist, a function of the model * If the field name is a method of the model, it'll be called, and the
will be searched for and called if present. This function output will be displayed. This method should have a
should have a ``short_description`` attribute that will be ``short_description`` function attribute, for use as the header for
used as the header for the field. the field.
See the exmaple below. See the example below.
``list_filter`` ``list_filter``
List of fields to filter by. Each field should either be a ``BooleanField`` List of fields to filter by. Each field should either be a ``BooleanField``
or else a field with a ``ManyToOne`` relation. or else a field with a ``ManyToOne`` relation.
An example of how ``list_display`` and ``list_filter`` work (taken from Here's an example of how ``list_display`` and ``list_filter`` work (taken
the ``auth.user`` model):: from the ``auth.user`` model)::
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'), list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
list_filter = ('is_staff', 'is_superuser'), list_filter = ('is_staff', 'is_superuser'),
results in a admin that looks like: This results in a admin that looks like:
.. image:: http://media.djangoproject.com/img/doc/users_changelist.png .. image:: http://media.djangoproject.com/img/doc/users_changelist.png
@ -620,8 +631,8 @@ object, which has the following options (of which only ``fields`` is required):
``ordering`` ``ordering``
An ordering tuple (see the `Options for models`_, above) that gives a An ordering tuple (see the `Options for models`_, above) that gives a
different ordering for the admin change list. If not given, the model's different ordering for the admin change list. If this isn't given, the
default ordering will be used. model's default ordering will be used.
``save_as`` ``save_as``
Enables a "save as" feature on object pages. Normally, objects have three Enables a "save as" feature on object pages. Normally, objects have three
@ -629,13 +640,17 @@ object, which has the following options (of which only ``fields`` is required):
another". If ``save_as`` is ``True``, "Save and add another" will be another". If ``save_as`` is ``True``, "Save and add another" will be
replaced by a "Save as" button. replaced by a "Save as" button.
"Save as" means the object will be saved as a new object (with a new ID),
rather than the old object.
``save_on_top`` ``save_on_top``
If this option is ``True``, object pages will have the save buttons across If this option is ``True``, object pages will have the save buttons across
the top as well as at the bottom of the page. the top as well as at the bottom of the page.
``search_fields`` ``search_fields``
A list of fields to provide a text search for. These fields should, A list of field names to provide a text search for. These fields should,
obviously, be some kind of text field. obviously, be some kind of text field, such as ``CharField`` or
``TextField``.
Model methods Model methods
============= =============
@ -650,15 +665,15 @@ of object instances. For example::
) )
def is_disgusting(self): def is_disgusting(self):
return "anchovices" in [topping.name for topping in self.get_topping_list()] return "anchovies" in [topping.name for topping in self.get_topping_list()]
Now, every ``Pizza`` object will have a ``is_disgusting()`` method. Now, every ``Pizza`` object will have a ``is_disgusting()`` method.
There are a few object methods that have special meaning: There are a few object methods that have special meaning:
``__repr__`` ``__repr__``
Django uses ``repr(obj)`` in a number of places, the most notable as the Django uses ``repr(obj)`` in a number of places, most notably as the value
value inserted into a template when it displays an object. Thus, you should inserted into a template when it displays an object. Thus, you should
return a nice, human-readable string for the object's ``__repr__``. return a nice, human-readable string for the object's ``__repr__``.
``get_absolute_url`` ``get_absolute_url``
@ -668,25 +683,26 @@ There are a few object methods that have special meaning:
def get_absolute_url(self): def get_absolute_url(self):
return "/pizzas/%i/" % self.id return "/pizzas/%i/" % self.id
The most useful place this is used is in the admin interface; if an object The most useful place this is used is in the admin interface. If an object
defines ``get_absolute_url`` then the object detail page will have a "View defines ``get_absolute_url``, the object detail page will have a "View on
on site" link that will jump you directly to the object's public view. site" link that will jump you directly to the object's public view.
``_pre_save`` ``_pre_save``
This method will be called just before the object is saved into the This method is called just before an object is saved to the database. For
database; you can use it to (for example) calculate aggregate values from example, you can use it to calculate aggregate values from other fields
other fields before the object is saved. before the object is saved.
``_post_save`` ``_post_save``
Called just after the object is saved to the database. This could be used This method is called just after the object is saved to the database. This
to update other tables, update cached information, etc. could be used to update other tables, update cached information, etc.
Module-level methods Module-level methods
-------------------- --------------------
Since each data class in effect turns into a module, there are times you'll want Since each data class effectively turns into a "magic" Python module under
to write methods that live in that module. Any model method that begins with ``django.models``, there are times you'll want to write methods that live in
"_module_" is turned into a module-level method:: that module. Any model method that begins with "_module_" is turned into a
module-level function::
class Pizza(meta.Model): class Pizza(meta.Model):
fields = ( fields = (
@ -703,8 +719,8 @@ method::
>>> pizzas.get_pizzas_to_deliver() >>> pizzas.get_pizzas_to_deliver()
[ ... ] [ ... ]
Note that the scope of these methods is modified to be the same has the module Note that the scope of these methods is modified to be the same as the module
scope (so that's how the raw ``get_list`` works). scope.
Manipulator methods Manipulator methods
------------------- -------------------
@ -712,7 +728,7 @@ Manipulator methods
Similarly, you can add methods to the object's manipulators (see the formfields Similarly, you can add methods to the object's manipulators (see the formfields
documentation for more on manipulators) by defining methods that being with documentation for more on manipulators) by defining methods that being with
"_manipulator_". This is most useful for providing custom validators for certain "_manipulator_". This is most useful for providing custom validators for certain
fields since manipulators automatically call any method that begins with fields because manipulators automatically call any method that begins with
"validate":: "validate"::
class Pizza(meta.Model): class Pizza(meta.Model):
@ -726,6 +742,3 @@ fields since manipulators automatically call any method that begins with
if int(field_data) in BAD_CUSTOMER_IDS: if int(field_data) in BAD_CUSTOMER_IDS:
raise validators.ValidationError("We don't deliver to this customer") raise validators.ValidationError("We don't deliver to this customer")