Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Beefed up docs/model-api.txt -- added a significant amount of documen…

…tation, links to example models and formatting changes

git-svn-id: http://code.djangoproject.com/svn/django/trunk@560 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit b8e1be6f46bb83f298f4b1d8b800fdd834016549 1 parent 75b5372
@adrianholovaty adrianholovaty authored
Showing with 519 additions and 321 deletions.
  1. +519 −321 docs/model-api.txt
View
840 docs/model-api.txt
@@ -2,244 +2,210 @@
Model reference
===============
-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
-document explains them.
+A model is the single, definitive source of data about your data. It contains
+the essential fields and behaviors of the data you're storing. Generally, each
+model maps to a single database table.
-META options
-============
+The basics:
-Give your model metadata by using an inner ``"class META"``, like so::
+ * Each model is a Python class that subclasses ``django.core.meta.Model``.
+ * Each attribute of the model represents a database field.
+ * Model metadata (non-field information) goes in an inner class named ``META``.
- class Foo(meta.Model):
- bar = meta.CharField(maxlength=30)
- # ...
- class META:
- admin = meta.Admin()
- # ...
+A companion to this document is the `official repository of model examples`_.
-Here's a list of all possible ``META`` options. No options are required.
+.. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/
-``admin``
- A ``meta.Admin`` object; see `Admin options`_. If this field is given, the
- object will have an admin interface. If it isn't given, the object won't
- have one.
+Field objects
+=============
-``db_table``
- The name of the database table to use for the module::
+The most important part of a model is the list of database fields it defines.
+Fields are defined by class attributes. Each class attribute in a model, aside
+from the optional inner ``class META``, should be an instance of a
+``meta.Field`` subclass.
- db_table = "pizza_orders"
+In this example, there are two fields, ``first_name`` and ``last_name`` ::
- If this isn't given, Django will use ``app_label + '_' + module_name``.
+ class Person(meta.Model):
+ first_name = meta.CharField(maxlength=30)
+ last_name = meta.CharField(maxlength=30)
-``exceptions``
- Names of extra exception subclasses to include in the generated module.
- These exceptions are available from instance methods and from module-level
- methods::
+Django will use ``first_name`` and ``last_name`` as the database column names.
- exceptions = ("DisgustingToppingsException", "BurntCrust")
+Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
+``OneToOneField``, takes an optional first positional argument -- a
+human-readable name. If the human-readable name isn't given, Django will use
+the machine-readable name, converting underscores to spaces.
-``get_latest_by``
- The name of a ``DateField`` or ``DateTimeField``; if given, the module will
- have a ``get_latest()`` function that fetches the "latest" object according
- to that field::
+Example::
- get_latest_by = "order_date"
+ first_name = meta.CharField("Person's first name", maxlength=30)
-``module_constants``
- A dictionary of names/values to use as extra module-level constants::
+For ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField``, use the
+``verbose_name`` keyword argument::
- module_constants = {
- 'MEAT_TYPE_PEPPERONI' : 1,
- 'MEAT_TYPE_SAUSAGE' : 2,
- }
+ poll = meta.ForeignKey(Poll, "the related poll")
+ sites = meta.ManyToManyField(Site, verbose_name="list of sites")
+ place = meta.OneToOneField(Place, verbose_name="related place")
-``module_name``
- The name of the module::
+Convention is not to capitalize the first letter of the ``verbose_name``.
+Django will automatically capitalize the first letter where it needs to.
- module_name = "pizza_orders"
+General field options
+---------------------
- If this isn't given, Django will use a lowercased version of the class
- name, plus "s".
+The following arguments are available to all field types. All are optional.
-``order_with_respect_to``
- Marks this object as "orderable" with respect to the given field. This is
- almost always used with related objects to allow them to be ordered with
- respect to a parent object. For example, if a ``PizzaToppping`` relates to
- a ``Pizza`` object, you might use::
+``null``
+ If ``True``, Django will store empty values as ``NULL`` in the database.
+ Default is ``False``.
- order_with_respect_to = 'pizza'
+ Note that empty string values will always get stored as empty strings, not
+ as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
+ booleans and dates.
- to allow the toppings to be ordered with respect to the associated pizza.
+ Avoid using ``null`` on string-based fields such as ``CharField`` and
+ ``TextField`` unless you have an excellent reason. If a string-based field
+ has ``null=True``, that means it has two possible values for "no data":
+ ``NULL``, and the empty string. In most cases, it's redundant to have two
+ possible values for "no data;" Django convention is to use the empty
+ string, not ``NULL``.
-``ordering``
- The default ordering for the object, for use by ``get_list`` and the admin::
+``blank``
+ If ``True``, the field is allowed to be blank.
- ordering = ['-order_date']
+ Note that this is different than ``null``. ``null`` is purely
+ database-related, whereas ``blank`` is validation-related. If a field has
+ ``blank=True``, validation on Django's admin site will allow entry of an
+ empty value. If a field has ``blank=False``, the field will be required.
- This is a tuple or list of strings. Each string is a field name with an
- optional "-" (indicating descending order). Or, you can use the string "?"
- to order randomly.
+``choices``
+ A list of 2-tuples to use as choices for this field.
-``permissions``
- Extra permissions to enter into the permissions table when creating this
- object. A add, delete, and change permission is automatically created for
- each object. This option specifies extra permissions::
+ If this is given, Django's admin will use a select box instead of the
+ standard text field and will limit choices to the choices given.
- permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
+ A choices list looks like this::
- This is a list of 2-tuples of
- ``(permission_code, human_readable_permission_name)``.
+ YEAR_IN_SCHOOL_CHOICES = (
+ ('FR', 'Freshman'),
+ ('SO', 'Sophomore'),
+ ('JR', 'Junior'),
+ ('SR', 'Senior'),
+ ('GR', 'Graduate'),
+ )
-``unique_together``
- Sets of field names that, taken together, must be unique::
+ The first element in each tuple is the actual value to be stored. The
+ second element is the human-readable name for the option.
- unique_together = (("driver", "restaurant"),)
+``core``
+ For objects that are edited inline to a related object.
- This is a list of lists of fields that must be unique when considered
- together. It's used in the Django admin.
+ In the Django admin, if all "core" fields in an inline-edited object are
+ cleared, the object will be deleted.
-``verbose_name``
- A human-readable name for the object, singular::
+ It is an error to have an inline-editable relation without at least one
+ ``core=True`` field.
- verbose_name = "pizza"
+``db_column``
+ The name of the database column to use for this field. If this isn't given,
+ Django will use the field's name.
- If this isn't given, Django will use a munged version of the class name:
- ``CamelCase`` becomes ``camel case``.
+``db_index``
+ If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
+ statement for this field.
-``verbose_name_plural``
- The plural name for the object::
+``default``
+ The default value for the field.
- verbose_name_plural = "stories"
+``editable``
+ If ``False``, the field will not be editable in the admin. Default is ``True``.
- If this isn't given, Django will use ``verbose_name + "s"``.
+``help_text``
+ Extra "help" text to be displayed under the field on the object's admin
+ form. It's useful for documentation even if your object doesn't have an
+ admin form.
-Field objects
-=============
+``primary_key``
+ If ``True``, this field is the primary key for the model.
-The list of fields is the most important part of a data model. Each class
-variable in a model, aside from the optional inner ``class META``, should be
-an instance of a ``meta.Field`` subclass.
+ If you don't specify ``primary_key=True`` for any fields in your model,
+ Django will automatically add this field::
-Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
-``OneToOneField``, takes an optional first positional argument, a
-human-readable name. If the human-readable name isn't given, Django will use
-the machine-readable name, converting underscores to spaces.
+ id = meta.AutoField('ID', primary_key=True)
-General field options
----------------------
+ Thus, you don't need to set ``primary_key=True`` on any of your fields
+ unless you want to override the default primary-key behavior.
+
+ ``primary_key=True`` implies ``blank=False``, ``null=False`` and
+ ``unique=True``. Only one primary key is allowed on an object.
+
+``radio_admin``
+ By default, Django's admin uses a select-box interface (<select>) for
+ fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
+ is set to ``True``, Django will use a radio-button interface instead.
+
+ Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
+ set.
+
+``unique``
+ If ``True``, this field must be unique throughout the table.
-Each type of field takes a different set of arguments, but some arguments are
-common to all field types. These arguments are:
-
- ====================== ===================================================
- Argument Description
- ====================== ===================================================
- ``blank`` If ``True``, the field is allowed to be blank.
- Note that this is different from ``null`` in that
- string fields will store the empty string instead of
- ``NULL`` internally. This means that to create a
- field that stores nulls you must pass ``blank=True``
- and ``null=True``.
-
- ``choices`` A list of 2-tuples to use as choices for this
- field. If this is given, Django's admin will use a
- select box instead of the standard text field and
- will limit choices to the choices given. A choices
- list looks like::
-
- YEAR_IN_SCHOOL_CHOICES = (
- ('FR', 'Freshman'),
- ('SO', 'Sophomore'),
- ('JR', 'Junior'),
- ('SR', 'Senior'),
- ('GR', 'Graduate'),
- )
-
- The first element in each tuple is the actual value
- to be stored. The second element is the
- human-readable name for the option.
-
- ``core`` For objects that are edited inline to a related
- object. If all "core" fields in an inline-edited
- object are cleared, the object will be considered to
- be deleted.
-
- It is an error to have an inline-editable
- relation without at least one core field.
-
- ``db_column`` The name of the database column to use for this
- field. If this isn't given, Django will use the
- field's name.
-
- ``db_index`` If ``True``, the SQL generator will create a database
- index on this field.
-
- ``default`` The default value for the field.
-
- ``editable`` ``True`` by default. If this is set to ``False``,
- the field will not be editable in the admin.
-
- ``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
- stored as ``NULL`` in the database.
-
- ``primary_key`` If ``True``, this field is the primary key for the
- table. You only need to use this if you don't want
- the standard "id" field created and used as the
- primary key.
-
- Implies ``blank=False``, ``null=False``, and
- ``unique=True``. Only one primary key is allowed
- on an object.
-
- ``radio_admin`` If ``choices`` is given, or if the field is a
- ManyToOne relation, use a radio-button interface
- for the choices instead of the standard select-box
- interface.
-
- ``unique`` If ``True``, this field must be unique throughout
- 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
- ``DateTimeField`` to require that this field
- be unique for the value of the date field. For
- example, if you have a field ``title`` that has
- ``unique_for_date="pub_date"``, then it is an
- error to have two rows with the same ``title``
- and the same ``pub_date``.
-
- ``unique_for_month`` Like ``unique_for_date``, but requires the field
- to be unique with respect to the month.
-
- ``unique_for_year`` Like ``unique_for_date`` and ``unique_for_month``.
-
- ``validator_list`` A list of extra validators to apply to the field.
- ====================== ===================================================
-
-Field Types
+ 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 ``DateTimeField`` to require
+ that this field be unique for the value of the date field.
+
+ For example, if you have a field ``title`` that has
+ ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
+ two records with the same ``title`` and ``pub_date``.
+
+ This is enforced at the Django admin-form level but not at the database level.
+
+``unique_for_month``
+ Like ``unique_for_date``, but requires the field to be unique with respect
+ to the month.
+
+``unique_for_year``
+ Like ``unique_for_date`` and ``unique_for_month``.
+
+``validator_list``
+ A list of extra validators to apply to the field.
+
+Field types
-----------
-``AutoField``
- An ``IntegerField`` that automatically increments. You usually won't need to
- 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::
+Each field in your model should be an instance of the appropriate ``Field``
+class. Django uses the field class types to determine a few things:
+
+ * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
+ * The widget to use in Django's admin (e.g. ``<input type="text">``, ``<select>``).
+ * The minimal validation requirements, used in Django's admin and in manipulators.
- id = meta.AutoField(primary_key=True)
+Here are all available field types:
+
+``AutoField``
+ An ``IntegerField`` that automatically increments according to available
+ IDs. You usually won't need to use this directly; a primary key field will
+ automatically be added to your model if you don't specify otherwise. (See
+ ``primary_key`` in ``General field options`` above.)
``BooleanField``
A true/false field.
+ The admin represents this as a checkbox.
+
``CharField``
- A text field. These are displayed in the admin as single-line text inputs.
+ A string field, for small- to large-sized strings.
+
For large amounts of text, use ``TextField``.
- ``CharField`` has an extra required argument: ``maxlength``, the maximum
- length (in characters) of the field. The maxlength is enforced at the database
- level and in Django's admin validation.
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+ ``CharField`` has an extra required argument, ``maxlength``, the maximum
+ length (in characters) of the field. The maxlength is enforced at the
+ database level and in Django's validation.
``CommaSeparatedIntegerField``
A field of integers separated by commas. As in ``CharField``, the
@@ -256,23 +222,32 @@ Field Types
timestamps.
``auto_now_add`` Automatically set the field to now when the object
- is first created. Useful for creation of
+ is first created. Useful for creation of
timestamps.
====================== ===================================================
+ The admin represents this as an ``<input type="text">`` with a JavaScript
+ calendar and a shortcut for "Today."
+
``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``.
+
+ The admin represents this as two ``<input type="text">`` fields, with
+ JavaScript shortcuts.
``EmailField``
A ``CharField`` that checks that the value is a valid e-mail address.
- Because validating e-mail addresses can be tricky, this is a pretty loose
- test.
+ Currently, this is a loose test.
``FileField``
- A file-upload field. Takes an additional option, ``upload_to``, which is
- a local filesystem path to upload the file to. This path may contain
- `strftime formatting`_, which will be replaced by the date/time of the file
- upload (so that uploaded files don't fill up the given directory).
+ A file-upload field.
+
+ Has an extra required argument, ``upload_to``, a local filesystem path to
+ which files should be upload. This path may contain `strftime formatting`_,
+ which will be replaced by the date/time of the file upload (so that
+ uploaded files don't fill up the given directory).
+
+ The admin represents this as an ``<input type="file">`` (a file-upload widget).
.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
@@ -285,7 +260,7 @@ Field Types
``max_digits`` The maximum number of digits allowed in the number.
``decimal_places`` The number of decimal places to store with the
- number
+ number.
====================== ===================================================
For example, to store numbers up to 999 with a resolution of 2 decimal places,
@@ -297,20 +272,136 @@ Field Types
meta.FloatField(..., max_digits=19, decimal_places=10)
-``ForeignKey``
- A many-to-one relationship to the primary key in another object. So, to give a
- ``Topping`` object a many-to-one relationship to ``Pizza`` (i.e. there are
- many toppings on a pizza)::
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+``ImageField``
+ Like ``FileField``, but validates that the uploaded object is a valid
+ 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 each time a model instance is saved.
+
+ Requires the `Python Imaging Library`_.
+
+ .. _Python Imaging Library: http://www.pythonware.com/products/pil/
+
+``IntegerField``
+ An integer.
+
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+``IPAddressField``
+ An IP address, in string format (i.e. "24.124.1.30").
+
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+``NullBooleanField``
+ Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this
+ instead of a ``BooleanField`` with ``null=True``.
+
+ The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
+
+``PhoneNumberField``
+ A ``CharField`` that checks that the value is a valid U.S.A.-style phone
+ number (in the format ``XXX-XXX-XXXX``).
+
+``PositiveIntegerField``
+ Like an ``IntegerField``, but must be positive.
+
+``PositiveSmallIntegerField``
+ Like a ``PositiveIntegerField``, but only allows values under a certain
+ (database-dependent) point.
+
+``SlugField``
+ "Slug" is a newspaper term. A slug is a short label for something,
+ containing only letters, numbers and underscores. They're generally used in
+ URLs.
+
+ Implies ``maxlength=50`` and ``db_index=True``.
+
+ Accepts an extra option, ``prepopulate_from``, which is a list of fields
+ from which to auto-populate the slug, via JavaScript, in the object's admin
+ form::
+
+ meta.SlugField(prepopulate_from=("pre_name", "name"))
+
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+``SmallIntegerField``
+ Like an ``IntegerField``, but only allows values under a certain
+ (database-dependent) point.
+
+``TextField``
+ A large text field.
+
+ The admin represents this as a ``<textarea>`` (a multi-line input).
+
+``TimeField``
+ A time. Accepts the same auto-population options as ``DateField`` and
+ ``DateTimeField``.
+
+ The admin represents this as an ``<input type="text">`` with some
+ JavaScript shortcuts.
+
+``URLField``
+ A field for a URL. If the ``verify_exists`` option is ``True`` (default),
+ the URL given will be checked for existence (i.e., the URL actually loads
+ and doesn't give a 404 response).
+
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+``USStateField``
+ A two-letter U.S. state abbreviation.
+
+ The admin represents this as an ``<input type="text">`` (a single-line input).
+
+``XMLField``
+ A ``TextField`` that checks that the value is valid XML that matches a
+ given schema. Takes one required argument, ``schema_path``, which is the
+ filesystem path to a RelaxNG_ schema against which to validate the field.
+
+ .. _RelaxNG: http://www.relaxng.org/
+
+Relationships
+-------------
+
+Clearly, the power of relational databases lies in relating tables to each
+other. Django offers ways to define the most common types of database
+relationships: Many-to-one, many-to-many and one-to-one.
+
+Many-to-one relationships
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To define a many-to-one relationship, use ``ForeignKey``. You use it just like
+any other ``Field`` type: by including it as a class attribute of your model.
+
+``ForeignKey`` requires a positional argument: The class to which the model is
+related.
+
+For example, if a ``Place`` model is in a ``City`` -- that is, a ``City``
+contains multiple places but each ``Place`` is only in one ``City`` -- here's
+how you'd represent that::
+
+ class City(meta.Model):
+ # ...
+
+ class Place(meta.Model):
+ # ...
+ city = meta.ForeignKey(City)
- meta.ForeignKey(Pizza)
+To create a recursive relationship -- an object that has a many-to-one
+relationship with itself -- use ``meta.ForeignKey("self")``.
- .. admonition:: Note
+The name of a ``ForeignKey`` (``pizza`` in the example above) generally should
+be the name of the model, singular. Behind the scenes, Django appends "_id" to
+the field name to create its database column name. But your code should never
+have to deal with the database column name, unless you write custom SQL.
- To create a recursive relationship, use a ``ForeignKey`` that relates
- to ``"self"`` (i.e. ``meta.ForeignKey("self")``).
+See the ``Many-to-one relationship model example_ for a full example.
- ``ForeignKey`` fields take a large number of extra arguments for defining how
- the relationship should work. All are optional:
+.. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
+
+``ForeignKey`` fields take a number of extra arguments for defining how the
+relationship should work. All are optional:
======================= ============================================================
Argument Description
@@ -376,8 +467,8 @@ Field Types
meta.ForeignKey(Pizza)
the ``related_name`` will be "topping" (taken from
- the class name which will in turn give ``Pizza``
- methods like ``get_topping_list()`` and
+ the class name), which will in turn give ``Pizza``
+ the methods ``get_topping_list()`` and
``get_topping_count()``.
If you instead were to use::
@@ -392,63 +483,72 @@ Field Types
object that relates to the same object more than
once. For example, if a ``Story`` object has both
``primary_category`` and ``secondary_category``
- fields, to make sure that the category objects
+ fields, to make sure that the ``Category`` objects
have the correct methods, you'd use fields like::
- ...
- meta.ForeignKey(Category, name="primary_category_id",
- related_name="primary_story"),
-
- meta.ForeignKey(Category, name="secondary_category_id",
- related_name="secondary_story"),
- ...
+ meta.ForeignKey(Category, related_name="primary_story")
+ meta.ForeignKey(Category, related_name="secondary_story")
- which would give the category objects methods
- named ``get_primary_story_list()`` and
+ ...which would give the ``Category`` objects
+ methods named ``get_primary_story_list()`` and
``get_secondary_story_list()``.
``to_field`` The field on the related object that the relation
- is to. This is almost always ``id``, but if the
- primary key on the other object is named something
- different, this is how to indicate that.
+ is to. By default, Django uses the primary key of
+ the related object.
======================= ============================================================
.. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
-``ImageField``
- Like a ``FileField``, but validates that the uploaded object is a valid
- 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.
+Many-to-many relationships
+~~~~~~~~~~~~~~~~~~~~~~~~~~
- Requires the `Python Imaging Library`_.
+To define a many-to-one relationship, use ``ManyToManyField``. You use it just
+like any other ``Field`` type: by including it as a class attribute of your
+model.
- .. _Python Imaging Library: http://www.pythonware.com/products/pil/
+``ManyToManyField`` requires a positional argument: The class to which the
+model is related.
-``IntegerField``
- An integer.
+For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
+``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
+here's how you'd represent that::
-``IPAddressField``
- An IP address, in string format (i.e. "24.124.1.30").
+ class Topping(meta.Model):
+ # ...
-``ManyToManyField``
- A many-to-many relation to another object. For example (taken from the
- ``core.flatfiles`` object::
+ class Pizza(meta.Model):
+ # ...
+ toppings = meta.ManyToManyField(Topping)
- class FlatFile(meta.Model):
- # ...
- sites = meta.ManyToManyField(Site)
+The name of a ``ManyToManyField`` (``toppings`` in the example above) generally
+should be the name of the model, plural.
+
+Behind the scenes, Django creates an intermediary join table to represent the
+many-to-many relationship.
+
+It doesn't matter which model gets the ``ManyToManyField``, but you only need
+it in one of the models -- not in both.
+
+Generally, ``ManyToManyField`` instances should go in the object that's going
+to be edited in the admin. In the above example, ``toppings`` is in ``Pizza``
+(rather than ``Topping`` having a ``pizzas`` ``ManyToManyField`` ) because it's
+more natural to think about a ``Pizza`` having toppings than a topping being on
+multiple pizzas. The way it's set up above, the ``Pizza`` admin form would let
+users select the toppings.
- Many-to-many relations are a bit different from other fields. First, they
- aren't actually a field per se, because they use a intermediary join table.
- Second, they don't take the same options as the rest of the fields. The
- first position argument is required and should be a model class. Other
- available arguments, all of which are optional, are:
+See the ``Many-to-many relationship model example_ for a full example.
+
+.. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
+
+``ManyToManyField`` objects take a number of extra arguments for defining how
+the relationship should work. All are optional:
======================= ============================================================
Argument Description
======================= ============================================================
``related_name`` See the description of ``related_name`` in
- ``ForeignKey``, above.
+ ``ForeignKey`` above.
``filter_interface`` Use a nifty unobtrusive Javascript "filter" interface
instead of the usability-challenged ``<select multiple>``
@@ -458,92 +558,171 @@ Field Types
vertically).
``limit_choices_to`` See the description under ``ForeignKey`` above.
-
- ``verbose_name`` A human-readable name for the object, singular. If
- this isn't provided, Django uses the
- ``verbose_name`` for the related object.
======================= ============================================================
-``NullBooleanField``
- Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this
- instead of a ``BooleanField`` with ``null=True``.
+One-to-one relationships
+~~~~~~~~~~~~~~~~~~~~~~~~
-``OneToOneField``
- Signifies a one-to-one relationship. This is most useful on the primary key
- of an object when that object "extends" another object in some way.
+To define a one-to-one relationship, use ``OneToOneField``. You use it just
+like any other ``Field`` type: by including it as a class attribute of your
+model.
- For example, if you are building a database of "places", you would build pretty
- standard stuff like address, phone number, etc. in the database. If you then
- wanted to build a database of restaurants on top of the places, instead of
- repeating yourself and replicating those fields in the restaurants object, you
- could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (since
- a restaurant "is-a" place). This ``OneToOneField`` will actually replace
- the primary key ``id`` field (since one-to-one relations share the same
- primary key), and has a few in the admin interface:
+This is most useful on the primary key of an object when that object "extends"
+another object in some way.
- * No selection interface is displayed on ``Restaurant`` pages; there will
- be one (and only one) ``Restaurant`` for each place.
+``OneToOneField`` requires a positional argument: The class to which the
+model is related.
- * On the ``Restaurant`` change list, every single ``Place`` -- weather it
- has an associated ``Restaurant`` or not -- will be displayed. Adding
- a ``Restaurant`` to a ``Place`` just means filling out the required
- ``Restaurant`` fields.
+For example, if you're building a database of "places", you would build pretty
+standard stuff such as address, phone number, etc. in the database. Then, if you
+wanted to build a database of restaurants on top of the places, instead of
+repeating yourself and replicating those fields in the ``Restaurant`` model, you
+could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
+restaurant "is-a" place).
-``PhoneNumberField``
- Validates that the value is a valid phone number.
+This ``OneToOneField`` will actually replace the primary key ``id`` field
+(since one-to-one relations share the same primary key), and has a few
+differences in the admin interface:
-``PositiveIntegerField``
- Like an ``IntegerField``, but must be positive.
+ * No ``Place`` selection interface is displayed on ``Restaurant`` pages.
+ There will be one (and only one) ``Restaurant`` for each ``Place``.
-``PositiveSmallIntegerField``
- Like a ``PositiveIntegerField``, but only allows values under a certain
- (database-dependent) point.
+ * On the ``Restaurant`` change list, every ``Place`` -- whether it has an
+ associated ``Restaurant`` or not -- will be displayed. Adding a
+ ``Restaurant`` to a ``Place`` just means filling out the required
+ ``Restaurant`` fields.
-``SlugField``
- "Slug" is a newspaper term. A slug is a short label for something,
- containing only letters, numbers and underscores. They're generally used in
- URLs.
+See the ``One-to-one relationship model example_ for a full example.
- Implies ``maxlength=50`` and ``db_index=True``.
+.. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
- Accepts an extra option, ``prepopulate_from``, which is a list of fields
- from which to auto-populate the slug, via JavaScript, in the object's admin
- form::
+META options
+============
- meta.SlugField(prepopulate_from=("pre_name", "name")),
+Give your model metadata by using an inner ``"class META"``, like so::
-``SmallIntegerField``
- Like an ``IntegerField``, but only allows values under a certain
- (database-dependent) point.
+ class Foo(meta.Model):
+ bar = meta.CharField(maxlength=30)
+ # ...
+ class META:
+ admin = meta.Admin()
+ # ...
-``TextField``
- A large text field (``<textarea>`` in HTML).
+Model metadata is "anything that's not a field" -- ordering options, admin
+options, etc.
-``TimeField``
- A time. Accepts the same auto-population options as ``DateField`` and
- ``DateTimeField``.
+Here's a list of all possible ``META`` options. No options are required. Adding
+``class META`` to a model is completely optional.
-``URLField``
- A field for a URL. If the ``verify_exists`` option is ``True`` (default),
- the URL given will be checked for existence (i.e., the URL actually loads
- and doesn't give a 404 response).
+``admin``
+ A ``meta.Admin`` object; see `Admin options`_. If this field is given, the
+ object will have an admin interface. If it isn't given, the object won't
+ have one.
-``USStateField``
- A two-letter U.S. state abbreviation.
+``db_table``
+ The name of the database table to use for the module::
-``XMLField``
- A field containing XML. Takes one required argument, ``schema_path``, which
- is the filesystem path to a RelaxNG_ schema against which to validate the
- field.
+ db_table = "pizza_orders"
- .. _RelaxNG: http://www.relaxng.org/
+ If this isn't given, Django will use ``app_label + '_' + module_name``.
+
+``exceptions``
+ Names of extra exception subclasses to include in the generated module.
+ These exceptions are available from instance methods and from module-level
+ methods::
+
+ exceptions = ("DisgustingToppingsException", "BurntCrust")
+
+``get_latest_by``
+ The name of a ``DateField`` or ``DateTimeField``. If given, the module will
+ have a ``get_latest()`` function that fetches the "latest" object according
+ to that field::
+
+ get_latest_by = "order_date"
+
+ See `Getting the "latest" object`_ for a full example.
+
+ .. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/
+
+``module_constants``
+ A dictionary of names/values to use as extra module-level constants::
+
+ module_constants = {
+ 'MEAT_TYPE_PEPPERONI' : 1,
+ 'MEAT_TYPE_SAUSAGE' : 2,
+ }
+
+``module_name``
+ The name of the module::
+
+ module_name = "pizza_orders"
+
+ If this isn't given, Django will use a lowercased version of the class
+ name, plus "s". This "poor man's pluralization" is intentional: Any other
+ level of magic pluralization would get confusing.
+
+``order_with_respect_to``
+ Marks this object as "orderable" with respect to the given field. This is
+ almost always used with related objects to allow them to be ordered with
+ respect to a parent object. For example, if a ``PizzaToppping`` relates to
+ a ``Pizza`` object, you might use::
+
+ order_with_respect_to = 'pizza'
+
+ to allow the toppings to be ordered with respect to the associated pizza.
+
+``ordering``
+ The default ordering for the object, for use by ``get_list`` and the admin::
+
+ ordering = ['-order_date']
+
+ This is a tuple or list of strings. Each string is a field name with an
+ optional "-" prefix, which indicates descending order. Fields without a
+ leading "-" will be ordered ascending. Use the string "?" to order randomly.
+
+ See `Specifying ordering`_ for a full example.
+
+ .. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
+
+``permissions``
+ Extra permissions to enter into the permissions table when creating this
+ object. Add, delete and change permissions are automatically created for
+ each object. This option specifies extra permissions::
+
+ permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
+
+ This is a list of 2-tuples of
+ ``(permission_code, human_readable_permission_name)``.
+
+``unique_together``
+ Sets of field names that, taken together, must be unique::
+
+ unique_together = (("driver", "restaurant"),)
+
+ This is a list of lists of fields that must be unique when considered
+ together. It's used in the Django admin.
+
+``verbose_name``
+ A human-readable name for the object, singular::
+
+ verbose_name = "pizza"
+
+ If this isn't given, Django will use a munged version of the class name:
+ ``CamelCase`` becomes ``camel case``.
+
+``verbose_name_plural``
+ The plural name for the object::
+
+ verbose_name_plural = "stories"
+
+ If this isn't given, Django will use ``verbose_name + "s"``.
Admin options
=============
The ``admin`` field in the model tells Django how to construct the admin
interface for the object. The field is an instance of the ``meta.Admin``
-object, which has the following options. All are optional.
+object, which takes the following parameters. All are optional.
``date_hierarchy``
To allow filtering of objects in the admin by date, set ``date_hierarchy``
@@ -562,7 +741,7 @@ object, which has the following options. All are optional.
multiple fields on the same line, wrap those fields in their
own tuple.
- This key is required in the dict.
+ This key is required in the dictionary.
``classes``
Extra CSS classes to apply to the fieldset. This is a simple
@@ -594,7 +773,7 @@ object, which has the following options. All are optional.
If ``fields`` isn't given but a model does define ``admin`` as a
``meta.Admin`` object, Django will default to displaying each field that
isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
- the same order as the ``fields`` in the model.
+ the same order as the fields are defined in the model.
``js``
A list of strings representing URLs of JavaScript files to link into the
@@ -643,7 +822,7 @@ object, which has the following options. All are optional.
``save_as``
Enables a "save as" feature on object pages. Normally, objects have three
- save options: "Save", "Save and continue editing", and "Save and add
+ save options: "Save", "Save and continue editing" and "Save and add
another". If ``save_as`` is ``True``, "Save and add another" will be
replaced by a "Save as" button.
@@ -674,29 +853,49 @@ of object instances. For example::
Now, every ``Pizza`` object will have a ``is_disgusting()`` method.
-There are a few object methods that have special meaning:
+Note that the scope of custom methods is modified to be the same as the module
+scope. These methods do NOT have access to globals within your model's module.
+
+See `Giving models custom methods`_ for a full example.
+
+.. _Giving models custom methods: http://www.djangoproject.com/documentation/models/custom_methods/
+
+A few object methods have special meaning:
``__repr__``
Django uses ``repr(obj)`` in a number of places, most notably as the 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 always
return a nice, human-readable string for the object's ``__repr__``.
+ Although defining ``__repr__()`` isn't required, it's strongly encouraged.
+
+ See `Adding __repr__()`_ for a full example.
+
+ .. _Adding __repr__()_: http://www.djangoproject.com/documentation/models/repr/
+
``get_absolute_url``
- If an object defines a ``get_absolute_url`` method, it is used to
- associate a URL with an object. For example:
+ Define a ``get_absolute_url`` method to tell Django how to calculate the
+ URL for an object. For example::
def get_absolute_url(self):
return "/pizzas/%i/" % self.id
- The most useful place this is used is in the admin interface. If an object
- defines ``get_absolute_url``, the object detail page will have a "View on
- site" link that will jump you directly to the object's public view.
+ Django uses this in its admin interface. If an object defines
+ ``get_absolute_url``, the object detail page will have a "View on site"
+ link that will jump you directly to the object's public view.
+
+ It's good practice to use ``get_absolute_url()`` in templates, instead of
+ hard-coding your objects' URLs.
``_pre_save``
This method is called just before an object is saved to the database. For
example, you can use it to calculate aggregate values from other fields
before the object is saved.
+ See ``Adding hooks before/after saving and deleting_ for a full example.
+
+ .. _Adding hooks before/after saving and deleting: http://www.djangoproject.com/documentation/models/save_delete_hooks/
+
``_post_save``
This method is called just after the object is saved to the database. This
could be used to update other tables, update cached information, etc.
@@ -729,16 +928,15 @@ method::
[ ... ]
Note that the scope of these methods is modified to be the same as the module
-scope.
+scope. These methods do NOT have access to globals within your model's module.
Manipulator methods
-------------------
-Similarly, you can add methods to the object's manipulators (see the formfields
-documentation for more on manipulators) by defining methods that being with
-"_manipulator_". This is most useful for providing custom validators for certain
-fields because manipulators automatically call any method that begins with
-"validate"::
+Similarly, you can add methods to the object's manipulators by defining methods
+that being with "_manipulator_". This is most useful for providing custom
+validators for certain fields, because manipulators automatically call any
+method that begins with "validate"::
class Pizza(meta.Model):
# ...
@@ -748,4 +946,4 @@ fields because manipulators automatically call any method that begins with
from django.conf.settings import 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."
Please sign in to comment.
Something went wrong with that request. Please try again.