From b8e1be6f46bb83f298f4b1d8b800fdd834016549 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Fri, 26 Aug 2005 18:29:11 +0000 Subject: [PATCH] Beefed up docs/model-api.txt -- added a significant amount of documentation, links to example models and formatting changes git-svn-id: http://code.djangoproject.com/svn/django/trunk@560 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/model-api.txt | 846 ++++++++++++++++++++++++++++----------------- 1 file changed, 522 insertions(+), 324 deletions(-) diff --git a/docs/model-api.txt b/docs/model-api.txt index 16d7ca9e0c..794625811b 100644 --- a/docs/model-api.txt +++ b/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. - -``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. - -``db_table`` - The name of the database table to use for the module:: - - db_table = "pizza_orders" - - 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" - -``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". - -``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 "-" (indicating descending order). Or, you can use the string "?" - to order randomly. - -``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:: - - 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"``. +.. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/ Field objects ============= -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. +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. + +In this example, there are two fields, ``first_name`` and ``last_name`` :: + + class Person(meta.Model): + first_name = meta.CharField(maxlength=30) + last_name = meta.CharField(maxlength=30) + +Django will use ``first_name`` and ``last_name`` as the database column names. Each field type, except for ``ForeignKey``, ``ManyToManyField`` and -``OneToOneField``, takes an optional first positional argument, a +``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. +Example:: + + first_name = meta.CharField("Person's first name", maxlength=30) + +For ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField``, use the +``verbose_name`` keyword argument:: + + poll = meta.ForeignKey(Poll, "the related poll") + sites = meta.ManyToManyField(Site, verbose_name="list of sites") + place = meta.OneToOneField(Place, verbose_name="related place") + +Convention is not to capitalize the first letter of the ``verbose_name``. +Django will automatically capitalize the first letter where it needs to. + General field options --------------------- -Each type of field takes a different set of arguments, but some arguments are -common to all field types. These arguments are: +The following arguments are available to all field types. All are optional. - ====================== =================================================== - 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``. +``null`` + If ``True``, Django will store empty values as ``NULL`` in the database. + Default is ``False``. - ``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:: + 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. - YEAR_IN_SCHOOL_CHOICES = ( - ('FR', 'Freshman'), - ('SO', 'Sophomore'), - ('JR', 'Junior'), - ('SR', 'Senior'), - ('GR', 'Graduate'), - ) + 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``. - The first element in each tuple is the actual value - to be stored. The second element is the - human-readable name for the option. +``blank`` + If ``True``, the field is allowed to be blank. - ``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. + 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. - It is an error to have an inline-editable - relation without at least one core field. +``choices`` + A list of 2-tuples to use as choices for this 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. + 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. - ``db_index`` If ``True``, the SQL generator will create a database - index on this field. + A choices list looks like this:: - ``default`` The default value for the field. + YEAR_IN_SCHOOL_CHOICES = ( + ('FR', 'Freshman'), + ('SO', 'Sophomore'), + ('JR', 'Junior'), + ('SR', 'Senior'), + ('GR', 'Graduate'), + ) - ``editable`` ``True`` by default. If this is set to ``False``, - the field will not be editable in the admin. + The first element in each tuple is the actual value to be stored. The + second element is the human-readable name for the option. - ``help_text`` Extra "help" text to be displayed under the field - on the object's admin form. +``core`` + For objects that are edited inline to a related object. - ``null`` If ``True``, empty values in the field will be - stored as ``NULL`` in the database. + In the Django admin, if all "core" fields in an inline-edited object are + cleared, the object will be deleted. - ``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. + It is an error to have an inline-editable relation without at least one + ``core=True`` field. - Implies ``blank=False``, ``null=False``, and - ``unique=True``. Only one primary key is allowed - on an object. +``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. - ``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. +``db_index`` + If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX`` + statement for this field. - ``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. +``default`` + The default value for the field. - ``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``. +``editable`` + If ``False``, the field will not be editable in the admin. Default is ``True``. - ``unique_for_month`` Like ``unique_for_date``, but requires the field - to be unique with respect to the month. +``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. - ``unique_for_year`` Like ``unique_for_date`` and ``unique_for_month``. +``primary_key`` + If ``True``, this field is the primary key for the model. - ``validator_list`` A list of extra validators to apply to the field. - ====================== =================================================== + If you don't specify ``primary_key=True`` for any fields in your model, + Django will automatically add this field:: -Field Types + id = meta.AutoField('ID', primary_key=True) + + 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 (``, ```` (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 ```` 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 ```` 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 ```` (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 ```` (a single-line input). - meta.ForeignKey(Pizza) +``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. - .. admonition:: Note + Requires the `Python Imaging Library`_. - To create a recursive relationship, use a ``ForeignKey`` that relates - to ``"self"`` (i.e. ``meta.ForeignKey("self")``). + .. _Python Imaging Library: http://www.pythonware.com/products/pil/ - ``ForeignKey`` fields take a large number of extra arguments for defining how - the relationship should work. All are optional: +``IntegerField`` + An integer. + + The admin represents this as an ```` (a single-line input). + +``IPAddressField`` + An IP address, in string format (i.e. "24.124.1.30"). + + The admin represents this as an ```` (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 ```` (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 ``