Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Adrian Holovaty authored August 26, 2005

Showing 1 changed file with 519 additions and 321 deletions. Show diff stats Hide diff stats

  1. 840  docs/model-api.txt
840  docs/model-api.txt
@@ -2,244 +2,210 @@
2 2
 Model reference
3 3
 ===============
4 4
 
5  
-Django's models are the bread and butter of the framework.  There's a huge
6  
-array of options available to you when defining your data models. This
7  
-document explains them.
  5
+A model is the single, definitive source of data about your data. It contains
  6
+the essential fields and behaviors of the data you're storing. Generally, each
  7
+model maps to a single database table.
8 8
 
9  
-META options
10  
-============
  9
+The basics:
11 10
 
12  
-Give your model metadata by using an inner ``"class META"``, like so::
  11
+    * Each model is a Python class that subclasses ``django.core.meta.Model``.
  12
+    * Each attribute of the model represents a database field.
  13
+    * Model metadata (non-field information) goes in an inner class named ``META``.
13 14
 
14  
-    class Foo(meta.Model):
15  
-        bar = meta.CharField(maxlength=30)
16  
-        # ...
17  
-        class META:
18  
-            admin = meta.Admin()
19  
-            # ...
  15
+A companion to this document is the `official repository of model examples`_.
20 16
 
21  
-Here's a list of all possible ``META`` options. No options are required.
  17
+.. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/
22 18
 
23  
-``admin``
24  
-    A ``meta.Admin`` object; see `Admin options`_. If this field is given, the
25  
-    object will have an admin interface. If it isn't given, the object won't
26  
-    have one.
  19
+Field objects
  20
+=============
27 21
 
28  
-``db_table``
29  
-    The name of the database table to use for the module::
  22
+The most important part of a model is the list of database fields it defines.
  23
+Fields are defined by class attributes. Each class attribute in a model, aside
  24
+from the optional inner ``class META``, should be an instance of a
  25
+``meta.Field`` subclass.
30 26
 
31  
-        db_table = "pizza_orders"
  27
+In this example, there are two fields, ``first_name`` and ``last_name`` ::
32 28
 
33  
-    If this isn't given, Django will use ``app_label + '_' + module_name``.
  29
+    class Person(meta.Model):
  30
+        first_name = meta.CharField(maxlength=30)
  31
+        last_name = meta.CharField(maxlength=30)
34 32
 
35  
-``exceptions``
36  
-    Names of extra exception subclasses to include in the generated module.
37  
-    These exceptions are available from instance methods and from module-level
38  
-    methods::
  33
+Django will use ``first_name`` and ``last_name`` as the database column names.
39 34
 
40  
-        exceptions = ("DisgustingToppingsException", "BurntCrust")
  35
+Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
  36
+``OneToOneField``, takes an optional first positional argument -- a
  37
+human-readable name. If the human-readable name isn't given, Django will use
  38
+the machine-readable name, converting underscores to spaces.
41 39
 
42  
-``get_latest_by``
43  
-    The name of a ``DateField`` or ``DateTimeField``; if given, the module will
44  
-    have a ``get_latest()`` function that fetches the "latest" object according
45  
-    to that field::
  40
+Example::
46 41
 
47  
-        get_latest_by = "order_date"
  42
+    first_name = meta.CharField("Person's first name", maxlength=30)
48 43
 
49  
-``module_constants``
50  
-    A dictionary of names/values to use as extra module-level constants::
  44
+For ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField``, use the
  45
+``verbose_name`` keyword argument::
51 46
 
52  
-        module_constants = {
53  
-            'MEAT_TYPE_PEPPERONI' : 1,
54  
-            'MEAT_TYPE_SAUSAGE' : 2,
55  
-        }
  47
+    poll = meta.ForeignKey(Poll, "the related poll")
  48
+    sites = meta.ManyToManyField(Site, verbose_name="list of sites")
  49
+    place = meta.OneToOneField(Place, verbose_name="related place")
56 50
 
57  
-``module_name``
58  
-    The name of the module::
  51
+Convention is not to capitalize the first letter of the ``verbose_name``.
  52
+Django will automatically capitalize the first letter where it needs to.
59 53
 
60  
-        module_name = "pizza_orders"
  54
+General field options
  55
+---------------------
61 56
 
62  
-    If this isn't given, Django will use a lowercased version of the class
63  
-    name, plus "s".
  57
+The following arguments are available to all field types. All are optional.
64 58
 
65  
-``order_with_respect_to``
66  
-    Marks this object as "orderable" with respect to the given field.  This is
67  
-    almost always used with related objects to allow them to be ordered with
68  
-    respect to a parent object.  For example, if a ``PizzaToppping`` relates to
69  
-    a ``Pizza`` object, you might use::
  59
+``null``
  60
+    If ``True``, Django will store empty values as ``NULL`` in the database.
  61
+    Default is ``False``.
70 62
 
71  
-        order_with_respect_to = 'pizza'
  63
+    Note that empty string values will always get stored as empty strings, not
  64
+    as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
  65
+    booleans and dates.
72 66
 
73  
-    to allow the toppings to be ordered with respect to the associated pizza.
  67
+    Avoid using ``null`` on string-based fields such as ``CharField`` and
  68
+    ``TextField`` unless you have an excellent reason. If a string-based field
  69
+    has ``null=True``, that means it has two possible values for "no data":
  70
+    ``NULL``, and the empty string. In most cases, it's redundant to have two
  71
+    possible values for "no data;" Django convention is to use the empty
  72
+    string, not ``NULL``.
74 73
 
75  
-``ordering``
76  
-    The default ordering for the object, for use by ``get_list`` and the admin::
  74
+``blank``
  75
+    If ``True``, the field is allowed to be blank.
77 76
 
78  
-        ordering = ['-order_date']
  77
+    Note that this is different than ``null``. ``null`` is purely
  78
+    database-related, whereas ``blank`` is validation-related. If a field has
  79
+    ``blank=True``, validation on Django's admin site will allow entry of an
  80
+    empty value. If a field has ``blank=False``, the field will be required.
79 81
 
80  
-    This is a tuple or list of strings. Each string is a field name with an
81  
-    optional "-" (indicating descending order). Or, you can use the string "?"
82  
-    to order randomly.
  82
+``choices``
  83
+    A list of 2-tuples to use as choices for this field.
83 84
 
84  
-``permissions``
85  
-    Extra permissions to enter into the permissions table when creating this
86  
-    object. A add, delete, and change permission is automatically created for
87  
-    each object. This option specifies extra permissions::
  85
+    If this is given, Django's admin will use a select box instead of the
  86
+    standard text field and will limit choices to the choices given.
88 87
 
89  
-        permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
  88
+    A choices list looks like this::
90 89
 
91  
-    This is a list of 2-tuples of
92  
-    ``(permission_code, human_readable_permission_name)``.
  90
+        YEAR_IN_SCHOOL_CHOICES = (
  91
+            ('FR', 'Freshman'),
  92
+            ('SO', 'Sophomore'),
  93
+            ('JR', 'Junior'),
  94
+            ('SR', 'Senior'),
  95
+            ('GR', 'Graduate'),
  96
+        )
93 97
 
94  
-``unique_together``
95  
-    Sets of field names that, taken together, must be unique::
  98
+        The first element in each tuple is the actual value to be stored. The
  99
+        second element is the human-readable name for the option.
96 100
 
97  
-        unique_together = (("driver", "restaurant"),)
  101
+``core``
  102
+    For objects that are edited inline to a related object.
98 103
 
99  
-    This is a list of lists of fields that must be unique when considered
100  
-    together. It's used in the Django admin.
  104
+    In the Django admin, if all "core" fields in an inline-edited object are
  105
+    cleared, the object will be deleted.
101 106
 
102  
-``verbose_name``
103  
-    A human-readable name for the object, singular::
  107
+    It is an error to have an inline-editable relation without at least one
  108
+    ``core=True`` field.
104 109
 
105  
-        verbose_name = "pizza"
  110
+``db_column``
  111
+    The name of the database column to use for this field. If this isn't given,
  112
+    Django will use the field's name.
106 113
 
107  
-    If this isn't given, Django will use a munged version of the class name:
108  
-    ``CamelCase`` becomes ``camel case``.
  114
+``db_index``
  115
+    If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
  116
+    statement for this field.
109 117
 
110  
-``verbose_name_plural``
111  
-    The plural name for the object::
  118
+``default``
  119
+    The default value for the field.
112 120
 
113  
-        verbose_name_plural = "stories"
  121
+``editable``
  122
+    If ``False``, the field will not be editable in the admin. Default is  ``True``.
114 123
 
115  
-    If this isn't given, Django will use ``verbose_name + "s"``.
  124
+``help_text``
  125
+    Extra "help" text to be displayed under the field on the object's admin
  126
+    form. It's useful for documentation even if your object doesn't have an
  127
+    admin form.
116 128
 
117  
-Field objects
118  
-=============
  129
+``primary_key``
  130
+    If ``True``, this field is the primary key for the model.
119 131
 
120  
-The list of fields is the most important part of a data model. Each class
121  
-variable in a model, aside from the optional inner ``class META``, should be
122  
-an instance of a ``meta.Field`` subclass.
  132
+    If you don't specify ``primary_key=True`` for any fields in your model,
  133
+    Django will automatically add this field::
123 134
 
124  
-Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
125  
-``OneToOneField``, takes an optional first positional argument, a
126  
-human-readable name. If the human-readable name isn't given, Django will use
127  
-the machine-readable name, converting underscores to spaces.
  135
+        id = meta.AutoField('ID', primary_key=True)
128 136
 
129  
-General field options
130  
----------------------
  137
+    Thus, you don't need to set ``primary_key=True`` on any of your fields
  138
+    unless you want to override the default primary-key behavior.
  139
+
  140
+    ``primary_key=True`` implies ``blank=False``, ``null=False`` and
  141
+    ``unique=True``. Only one primary key is allowed on an object.
  142
+
  143
+``radio_admin``
  144
+    By default, Django's admin uses a select-box interface (<select>) for
  145
+    fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
  146
+    is set to ``True``, Django will use a radio-button interface instead.
  147
+
  148
+    Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
  149
+    set.
  150
+
  151
+``unique``
  152
+    If ``True``, this field must be unique throughout the table.
131 153
 
132  
-Each type of field takes a different set of arguments, but some arguments are
133  
-common to all field types. These arguments are:
134  
-
135  
-    ======================  ===================================================
136  
-    Argument                Description
137  
-    ======================  ===================================================
138  
-    ``blank``               If ``True``, the field is allowed to be blank.
139  
-                            Note that this is different from ``null`` in that
140  
-                            string fields will store the empty string instead of
141  
-                            ``NULL`` internally. This means that to create a
142  
-                            field that stores nulls you must pass ``blank=True``
143  
-                            and ``null=True``.
144  
-
145  
-    ``choices``             A list of 2-tuples to use as choices for this
146  
-                            field. If this is given, Django's admin will use a
147  
-                            select box instead of the standard text field and
148  
-                            will limit choices to the choices given.  A choices
149  
-                            list looks like::
150  
-
151  
-                                YEAR_IN_SCHOOL_CHOICES = (
152  
-                                    ('FR', 'Freshman'),
153  
-                                    ('SO', 'Sophomore'),
154  
-                                    ('JR', 'Junior'),
155  
-                                    ('SR', 'Senior'),
156  
-                                    ('GR', 'Graduate'),
157  
-                                )
158  
-
159  
-                            The first element in each tuple is the actual value
160  
-                            to be stored. The second element is the
161  
-                            human-readable name for the option.
162  
-
163  
-    ``core``                For objects that are edited inline to a related
164  
-                            object.  If all "core" fields in an inline-edited
165  
-                            object are cleared, the object will be considered to
166  
-                            be deleted.
167  
-
168  
-                            It is an error to have an inline-editable
169  
-                            relation without at least one core field.
170  
-
171  
-    ``db_column``           The name of the database column to use for this
172  
-                            field. If this isn't given, Django will use the
173  
-                            field's name.
174  
-
175  
-    ``db_index``            If ``True``, the SQL generator will create a database
176  
-                            index on this field.
177  
-
178  
-    ``default``             The default value for the field.
179  
-
180  
-    ``editable``            ``True`` by default. If this is set to ``False``,
181  
-                            the field will not be editable in the admin.
182  
-
183  
-    ``help_text``           Extra "help" text to be displayed under the field
184  
-                            on the object's admin form.
185  
-
186  
-    ``null``                If ``True``, empty values in the field will be
187  
-                            stored as ``NULL`` in the database.
188  
-
189  
-    ``primary_key``         If ``True``, this field is the primary key for the
190  
-                            table. You only need to use this if you don't want
191  
-                            the standard "id" field created and used as the
192  
-                            primary key.
193  
-
194  
-                            Implies ``blank=False``, ``null=False``, and
195  
-                            ``unique=True``. Only one primary key is allowed
196  
-                            on an object.
197  
-
198  
-    ``radio_admin``         If ``choices`` is given, or if the field is a
199  
-                            ManyToOne relation, use a radio-button interface
200  
-                            for the choices instead of the standard select-box
201  
-                            interface.
202  
-
203  
-    ``unique``              If ``True``, this field must be unique throughout
204  
-                            the table. This is enforced at the database level
205  
-                            and at the Django admin-form level.
206  
-
207  
-    ``unique_for_date``     Set this to the name of a ``DateField`` or
208  
-                            ``DateTimeField`` to require that this field
209  
-                            be unique for the value of the date field. For
210  
-                            example, if you have a field ``title`` that has
211  
-                            ``unique_for_date="pub_date"``, then it is an
212  
-                            error to have two rows with the same ``title``
213  
-                            and the same ``pub_date``.
214  
-
215  
-    ``unique_for_month``    Like ``unique_for_date``, but requires the field
216  
-                            to be unique with respect to the month.
217  
-
218  
-    ``unique_for_year``     Like ``unique_for_date`` and ``unique_for_month``.
219  
-
220  
-    ``validator_list``      A list of extra validators to apply to the field.
221  
-    ======================  ===================================================
222  
-
223  
-Field Types
  154
+    This is enforced at the database level and at the Django admin-form level.
  155
+
  156
+``unique_for_date``
  157
+    Set this to the name of a ``DateField`` or ``DateTimeField`` to require
  158
+    that this field be unique for the value of the date field.
  159
+
  160
+    For example, if you have a field ``title`` that has
  161
+    ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
  162
+    two records with the same ``title`` and ``pub_date``.
  163
+
  164
+    This is enforced at the Django admin-form level but not at the database level.
  165
+
  166
+``unique_for_month``
  167
+    Like ``unique_for_date``, but requires the field to be unique with respect
  168
+    to the month.
  169
+
  170
+``unique_for_year``
  171
+    Like ``unique_for_date`` and ``unique_for_month``.
  172
+
  173
+``validator_list``
  174
+    A list of extra validators to apply to the field.
  175
+
  176
+Field types
224 177
 -----------
225 178
 
226  
-``AutoField``
227  
-    An ``IntegerField`` that automatically increments. You usually won't need to
228  
-    use this directly; a primary key field will automatically be added to your
229  
-    model if you don't specify otherwise. That automatically-added field is::
  179
+Each field in your model should be an instance of the appropriate ``Field``
  180
+class. Django uses the field class types to determine a few things:
  181
+
  182
+    * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
  183
+    * The widget to use in Django's admin (e.g. ``<input type="text">``, ``<select>``).
  184
+    * The minimal validation requirements, used in Django's admin and in manipulators.
230 185
 
231  
-        id = meta.AutoField(primary_key=True)
  186
+Here are all available field types:
  187
+
  188
+``AutoField``
  189
+    An ``IntegerField`` that automatically increments according to available
  190
+    IDs. You usually won't need to use this directly; a primary key field will
  191
+    automatically be added to your model if you don't specify otherwise. (See
  192
+    ``primary_key`` in ``General field options`` above.)
232 193
 
233 194
 ``BooleanField``
234 195
     A true/false field.
235 196
 
  197
+    The admin represents this as a checkbox.
  198
+
236 199
 ``CharField``
237  
-    A text field. These are displayed in the admin as single-line text inputs.
  200
+    A string field, for small- to large-sized strings.
  201
+
238 202
     For large amounts of text, use ``TextField``.
239 203
 
240  
-    ``CharField`` has an extra required argument: ``maxlength``, the maximum
241  
-    length (in characters) of the field. The maxlength is enforced at the database
242  
-    level and in Django's admin validation.
  204
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  205
+
  206
+    ``CharField`` has an extra required argument, ``maxlength``, the maximum
  207
+    length (in characters) of the field. The maxlength is enforced at the
  208
+    database level and in Django's validation.
243 209
 
244 210
 ``CommaSeparatedIntegerField``
245 211
     A field of integers separated by commas. As in ``CharField``, the
@@ -256,23 +222,32 @@ Field Types
256 222
                                 timestamps.
257 223
 
258 224
         ``auto_now_add``        Automatically set the field to now when the object
259  
-                                is first created.  Useful for creation of
  225
+                                is first created. Useful for creation of
260 226
                                 timestamps.
261 227
         ======================  ===================================================
262 228
 
  229
+    The admin represents this as an ``<input type="text">`` with a JavaScript
  230
+    calendar and a shortcut for "Today."
  231
+
263 232
 ``DateTimeField``
264  
-    A date and time field.  Takes the same extra options as ``DateField``.
  233
+    A date and time field. Takes the same extra options as ``DateField``.
  234
+
  235
+    The admin represents this as two ``<input type="text">`` fields, with
  236
+    JavaScript shortcuts.
265 237
 
266 238
 ``EmailField``
267 239
     A ``CharField`` that checks that the value is a valid e-mail address.
268  
-    Because validating e-mail addresses can be tricky, this is a pretty loose
269  
-    test.
  240
+    Currently, this is a loose test.
270 241
 
271 242
 ``FileField``
272  
-    A file-upload field.  Takes an additional option, ``upload_to``, which is
273  
-    a local filesystem path to upload the file to. This path may contain
274  
-    `strftime formatting`_, which will be replaced by the date/time of the file
275  
-    upload (so that uploaded files don't fill up the given directory).
  243
+    A file-upload field.
  244
+
  245
+    Has an extra required argument, ``upload_to``, a local filesystem path to
  246
+    which files should be upload. This path may contain `strftime formatting`_,
  247
+    which will be replaced by the date/time of the file upload (so that
  248
+    uploaded files don't fill up the given directory).
  249
+
  250
+    The admin represents this as an ``<input type="file">`` (a file-upload widget).
276 251
 
277 252
     .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
278 253
 
@@ -285,7 +260,7 @@ Field Types
285 260
         ``max_digits``          The maximum number of digits allowed in the number.
286 261
 
287 262
         ``decimal_places``      The number of decimal places to store with the
288  
-                                number
  263
+                                number.
289 264
         ======================  ===================================================
290 265
 
291 266
     For example, to store numbers up to 999 with a resolution of 2 decimal places,
@@ -297,20 +272,136 @@ Field Types
297 272
 
298 273
         meta.FloatField(..., max_digits=19, decimal_places=10)
299 274
 
300  
-``ForeignKey``
301  
-    A many-to-one relationship to the primary key in another object. So, to give a
302  
-    ``Topping`` object a many-to-one relationship to ``Pizza`` (i.e. there are
303  
-    many toppings on a pizza)::
  275
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  276
+
  277
+``ImageField``
  278
+    Like ``FileField``, but validates that the uploaded object is a valid
  279
+    image. Has two extra optional arguments, ``height_field`` and
  280
+    ``width_field``, which, if set, will be auto-populated with the height and
  281
+    width of the image each time a model instance is saved.
  282
+
  283
+    Requires the `Python Imaging Library`_.
  284
+
  285
+    .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  286
+
  287
+``IntegerField``
  288
+    An integer.
  289
+
  290
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  291
+
  292
+``IPAddressField``
  293
+    An IP address, in string format (i.e. "24.124.1.30").
  294
+
  295
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  296
+
  297
+``NullBooleanField``
  298
+    Like a ``BooleanField``, but allows ``NULL`` as one of the options.  Use this
  299
+    instead of a ``BooleanField`` with ``null=True``.
  300
+
  301
+    The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
  302
+
  303
+``PhoneNumberField``
  304
+    A ``CharField`` that checks that the value is a valid U.S.A.-style phone
  305
+    number (in the format ``XXX-XXX-XXXX``).
  306
+
  307
+``PositiveIntegerField``
  308
+    Like an ``IntegerField``, but must be positive.
  309
+
  310
+``PositiveSmallIntegerField``
  311
+    Like a ``PositiveIntegerField``, but only allows values under a certain
  312
+    (database-dependent) point.
  313
+
  314
+``SlugField``
  315
+    "Slug" is a newspaper term. A slug is a short label for something,
  316
+    containing only letters, numbers and underscores. They're generally used in
  317
+    URLs.
  318
+
  319
+    Implies ``maxlength=50`` and ``db_index=True``.
  320
+
  321
+    Accepts an extra option, ``prepopulate_from``, which is a list of fields
  322
+    from which to auto-populate the slug, via JavaScript, in the object's admin
  323
+    form::
  324
+
  325
+        meta.SlugField(prepopulate_from=("pre_name", "name"))
  326
+
  327
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  328
+
  329
+``SmallIntegerField``
  330
+    Like an ``IntegerField``, but only allows values under a certain
  331
+    (database-dependent) point.
  332
+
  333
+``TextField``
  334
+    A large text field.
  335
+
  336
+    The admin represents this as a ``<textarea>`` (a multi-line input).
  337
+
  338
+``TimeField``
  339
+    A time. Accepts the same auto-population options as ``DateField`` and
  340
+    ``DateTimeField``.
  341
+
  342
+    The admin represents this as an ``<input type="text">`` with some
  343
+    JavaScript shortcuts.
  344
+
  345
+``URLField``
  346
+    A field for a URL. If the ``verify_exists`` option is ``True`` (default),
  347
+    the URL given will be checked for existence (i.e., the URL actually loads
  348
+    and doesn't give a 404 response).
  349
+
  350
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  351
+
  352
+``USStateField``
  353
+    A two-letter U.S. state abbreviation.
  354
+
  355
+    The admin represents this as an ``<input type="text">`` (a single-line input).
  356
+
  357
+``XMLField``
  358
+    A ``TextField`` that checks that the value is valid XML that matches a
  359
+    given schema. Takes one required argument, ``schema_path``, which is the
  360
+    filesystem path to a RelaxNG_ schema against which to validate the field.
  361
+
  362
+    .. _RelaxNG: http://www.relaxng.org/
  363
+
  364
+Relationships
  365
+-------------
  366
+
  367
+Clearly, the power of relational databases lies in relating tables to each
  368
+other. Django offers ways to define the most common types of database
  369
+relationships: Many-to-one, many-to-many and one-to-one.
  370
+
  371
+Many-to-one relationships
  372
+~~~~~~~~~~~~~~~~~~~~~~~~~
  373
+
  374
+To define a many-to-one relationship, use ``ForeignKey``. You use it just like
  375
+any other ``Field`` type: by including it as a class attribute of your model.
  376
+
  377
+``ForeignKey`` requires a positional argument: The class to which the model is
  378
+related.
  379
+
  380
+For example, if a ``Place`` model is in a ``City`` -- that is, a ``City``
  381
+contains multiple places but each ``Place`` is only in one ``City`` -- here's
  382
+how you'd represent that::
  383
+
  384
+    class City(meta.Model):
  385
+        # ...
  386
+
  387
+    class Place(meta.Model):
  388
+        # ...
  389
+        city = meta.ForeignKey(City)
304 390
 
305  
-        meta.ForeignKey(Pizza)
  391
+To create a recursive relationship -- an object that has a many-to-one
  392
+relationship with itself -- use ``meta.ForeignKey("self")``.
306 393
 
307  
-    .. admonition:: Note
  394
+The name of a ``ForeignKey`` (``pizza`` in the example above) generally should
  395
+be the name of the model, singular. Behind the scenes, Django appends "_id" to
  396
+the field name to create its database column name. But your code should never
  397
+have to deal with the database column name, unless you write custom SQL.
308 398
 
309  
-        To create a recursive relationship, use a ``ForeignKey`` that relates
310  
-        to ``"self"`` (i.e. ``meta.ForeignKey("self")``).
  399
+See the ``Many-to-one relationship model example_ for a full example.
311 400
 
312  
-    ``ForeignKey`` fields take a large number of extra arguments for defining how
313  
-    the relationship should work. All are optional:
  401
+.. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
  402
+
  403
+``ForeignKey`` fields take a number of extra arguments for defining how the
  404
+relationship should work. All are optional:
314 405
 
315 406
     =======================  ============================================================
316 407
     Argument                 Description
@@ -376,8 +467,8 @@ Field Types
376 467
                                     meta.ForeignKey(Pizza)
377 468
 
378 469
                              the ``related_name`` will be "topping" (taken from
379  
-                             the class name which will in turn give ``Pizza``
380  
-                             methods like ``get_topping_list()`` and
  470
+                             the class name), which will in turn give ``Pizza``
  471
+                             the methods ``get_topping_list()`` and
381 472
                              ``get_topping_count()``.
382 473
 
383 474
                              If you instead were to use::
@@ -392,63 +483,72 @@ Field Types
392 483
                              object that relates to the same object more than
393 484
                              once.  For example, if a ``Story`` object has both
394 485
                              ``primary_category`` and ``secondary_category``
395  
-                             fields, to make sure that the category objects
  486
+                             fields, to make sure that the ``Category`` objects
396 487
                              have the correct methods, you'd use fields like::
397 488
 
398  
-                                    ...
399  
-                                    meta.ForeignKey(Category, name="primary_category_id",
400  
-                                                    related_name="primary_story"),
401  
-
402  
-                                    meta.ForeignKey(Category, name="secondary_category_id",
403  
-                                                    related_name="secondary_story"),
404  
-                                    ...
  489
+                                    meta.ForeignKey(Category, related_name="primary_story")
  490
+                                    meta.ForeignKey(Category, related_name="secondary_story")
405 491
 
406  
-                             which would give the category objects methods
407  
-                             named ``get_primary_story_list()`` and
  492
+                             ...which would give the ``Category`` objects
  493
+                             methods named ``get_primary_story_list()`` and
408 494
                              ``get_secondary_story_list()``.
409 495
 
410 496
     ``to_field``             The field on the related object that the relation
411  
-                             is to. This is almost always ``id``, but if the
412  
-                             primary key on the other object is named something
413  
-                             different, this is how to indicate that.
  497
+                             is to. By default, Django uses the primary key of
  498
+                             the related object.
414 499
     =======================  ============================================================
415 500
 
416 501
 .. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
417 502
 
418  
-``ImageField``
419  
-    Like a ``FileField``, but validates that the uploaded object is a valid
420  
-    image. Has two extra optional arguments, ``height_field`` and ``width_field``
421  
-    which, if set, will be auto-populated with the height and width of the image.
  503
+Many-to-many relationships
  504
+~~~~~~~~~~~~~~~~~~~~~~~~~~
422 505
 
423  
-    Requires the `Python Imaging Library`_.
  506
+To define a many-to-one relationship, use ``ManyToManyField``. You use it just
  507
+like any other ``Field`` type: by including it as a class attribute of your
  508
+model.
424 509
 
425  
-    .. _Python Imaging Library: http://www.pythonware.com/products/pil/
  510
+``ManyToManyField`` requires a positional argument: The class to which the
  511
+model is related.
426 512
 
427  
-``IntegerField``
428  
-    An integer.
  513
+For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
  514
+``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
  515
+here's how you'd represent that::
429 516
 
430  
-``IPAddressField``
431  
-    An IP address, in string format (i.e. "24.124.1.30").
  517
+    class Topping(meta.Model):
  518
+        # ...
432 519
 
433  
-``ManyToManyField``
434  
-    A many-to-many relation to another object.  For example (taken from the
435  
-    ``core.flatfiles`` object::
  520
+    class Pizza(meta.Model):
  521
+        # ...
  522
+        toppings = meta.ManyToManyField(Topping)
436 523
 
437  
-        class FlatFile(meta.Model):
438  
-            # ...
439  
-            sites = meta.ManyToManyField(Site)
  524
+The name of a ``ManyToManyField`` (``toppings`` in the example above) generally
  525
+should be the name of the model, plural.
  526
+
  527
+Behind the scenes, Django creates an intermediary join table to represent the
  528
+many-to-many relationship.
  529
+
  530
+It doesn't matter which model gets the ``ManyToManyField``, but you only need
  531
+it in one of the models -- not in both.
  532
+
  533
+Generally, ``ManyToManyField`` instances should go in the object that's going
  534
+to be edited in the admin. In the above example, ``toppings`` is in ``Pizza``
  535
+(rather than ``Topping`` having a ``pizzas`` ``ManyToManyField`` ) because it's
  536
+more natural to think about a ``Pizza`` having toppings than a topping being on
  537
+multiple pizzas. The way it's set up above, the ``Pizza`` admin form would let
  538
+users select the toppings.
440 539
 
441  
-    Many-to-many relations are a bit different from other fields.  First, they
442  
-    aren't actually a field per se, because they use a intermediary join table.
443  
-    Second, they don't take the same options as the rest of the fields. The
444  
-    first position argument is required and should be a model class. Other
445  
-    available arguments, all of which are optional, are:
  540
+See the ``Many-to-many relationship model example_ for a full example.
  541
+
  542
+.. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
  543
+
  544
+``ManyToManyField`` objects take a number of extra arguments for defining how
  545
+the relationship should work. All are optional:
446 546
 
447 547
     =======================  ============================================================
448 548
     Argument                 Description
449 549
     =======================  ============================================================
450 550
     ``related_name``         See the description of ``related_name`` in
451  
-                             ``ForeignKey``, above.
  551
+                             ``ForeignKey`` above.
452 552
 
453 553
     ``filter_interface``     Use a nifty unobtrusive Javascript "filter" interface
454 554
                              instead of the usability-challenged ``<select multiple>``
@@ -458,92 +558,171 @@ Field Types
458 558
                              vertically).
459 559
 
460 560
     ``limit_choices_to``     See the description under ``ForeignKey`` above.
461  
-
462  
-    ``verbose_name``         A human-readable name for the object, singular. If
463  
-                             this isn't provided, Django uses the
464  
-                             ``verbose_name`` for the related object.
465 561
     =======================  ============================================================
466 562
 
467  
-``NullBooleanField``
468  
-    Like a ``BooleanField``, but allows ``NULL`` as one of the options.  Use this
469  
-    instead of a ``BooleanField`` with ``null=True``.
  563
+One-to-one relationships
  564
+~~~~~~~~~~~~~~~~~~~~~~~~
470 565
 
471  
-``OneToOneField``
472  
-    Signifies a one-to-one relationship.  This is most useful on the primary key
473  
-    of an object when that object "extends" another object in some way.
  566
+To define a one-to-one relationship, use ``OneToOneField``. You use it just
  567
+like any other ``Field`` type: by including it as a class attribute of your
  568
+model.
474 569
 
475  
-    For example, if you are building a database of "places", you would build pretty
476  
-    standard stuff like address, phone number, etc. in the database.  If you then
477  
-    wanted to build a database of restaurants on top of the places, instead of
478  
-    repeating yourself and replicating those fields in the restaurants object, you
479  
-    could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (since
480  
-    a restaurant "is-a" place).  This ``OneToOneField`` will actually replace
481  
-    the primary key ``id`` field (since one-to-one relations share the same
482  
-    primary key), and has a few in the admin interface:
  570
+This is most useful on the primary key of an object when that object "extends"
  571
+another object in some way.
483 572
 
484  
-        * No selection interface is displayed on ``Restaurant`` pages; there will
485  
-          be one (and only one) ``Restaurant`` for each place.
  573
+``OneToOneField`` requires a positional argument: The class to which the
  574
+model is related.
486 575
 
487  
-        * On the ``Restaurant`` change list, every single ``Place`` -- weather it
488  
-          has an associated ``Restaurant`` or not -- will be displayed. Adding
489  
-          a ``Restaurant`` to a ``Place`` just means filling out the required
490  
-          ``Restaurant`` fields.
  576
+For example, if you're building a database of "places", you would build pretty
  577
+standard stuff such as address, phone number, etc. in the database. Then, if you
  578
+wanted to build a database of restaurants on top of the places, instead of
  579
+repeating yourself and replicating those fields in the ``Restaurant`` model, you
  580
+could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
  581
+restaurant "is-a" place).
491 582
 
492  
-``PhoneNumberField``
493  
-    Validates that the value is a valid phone number.
  583
+This ``OneToOneField`` will actually replace the primary key ``id`` field
  584
+(since one-to-one relations share the same primary key), and has a few
  585
+differences in the admin interface:
494 586
 
495  
-``PositiveIntegerField``
496  
-    Like an ``IntegerField``, but must be positive.
  587
+    * No ``Place`` selection interface is displayed on ``Restaurant`` pages.
  588
+      There will be one (and only one) ``Restaurant`` for each ``Place``.
497 589
 
498  
-``PositiveSmallIntegerField``
499  
-    Like a ``PositiveIntegerField``, but only allows values under a certain
500  
-    (database-dependent) point.
  590
+    * On the ``Restaurant`` change list, every ``Place`` -- whether it has an
  591
+      associated ``Restaurant`` or not -- will be displayed. Adding a
  592
+      ``Restaurant`` to a ``Place`` just means filling out the required
  593
+      ``Restaurant`` fields.
501 594
 
502  
-``SlugField``
503  
-    "Slug" is a newspaper term. A slug is a short label for something,
504  
-    containing only letters, numbers and underscores. They're generally used in
505  
-    URLs.
  595
+See the ``One-to-one relationship model example_ for a full example.
506 596
 
507  
-    Implies ``maxlength=50`` and ``db_index=True``.
  597
+.. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
508 598
 
509  
-    Accepts an extra option, ``prepopulate_from``, which is a list of fields
510  
-    from which to auto-populate the slug, via JavaScript, in the object's admin
511  
-    form::
  599
+META options
  600
+============
512 601
 
513  
-        meta.SlugField(prepopulate_from=("pre_name", "name")),
  602
+Give your model metadata by using an inner ``"class META"``, like so::
514 603
 
515  
-``SmallIntegerField``
516  
-    Like an ``IntegerField``, but only allows values under a certain
517  
-    (database-dependent) point.
  604
+    class Foo(meta.Model):
  605
+        bar = meta.CharField(maxlength=30)
  606
+        # ...
  607
+        class META:
  608
+            admin = meta.Admin()
  609
+            # ...
518 610
 
519  
-``TextField``
520  
-    A large text field (``<textarea>`` in HTML).
  611
+Model metadata is "anything that's not a field" -- ordering options, admin
  612
+options, etc.
521 613
 
522  
-``TimeField``
523  
-    A time. Accepts the same auto-population options as ``DateField`` and
524  
-    ``DateTimeField``.
  614
+Here's a list of all possible ``META`` options. No options are required. Adding
  615
+``class META`` to a model is completely optional.
525 616
 
526  
-``URLField``
527  
-    A field for a URL.  If the ``verify_exists`` option is ``True`` (default),
528  
-    the URL given will be checked for existence (i.e., the URL actually loads
529  
-    and doesn't give a 404 response).
  617
+``admin``
  618
+    A ``meta.Admin`` object; see `Admin options`_. If this field is given, the
  619
+    object will have an admin interface. If it isn't given, the object won't
  620
+    have one.
530 621
 
531  
-``USStateField``
532  
-    A two-letter U.S. state abbreviation.
  622
+``db_table``
  623
+    The name of the database table to use for the module::
533 624
 
534  
-``XMLField``
535  
-    A field containing XML. Takes one required argument, ``schema_path``, which
536  
-    is the filesystem path to a RelaxNG_ schema against which to validate the
537  
-    field.
  625
+        db_table = "pizza_orders"
538 626
 
539  
-    .. _RelaxNG: http://www.relaxng.org/
  627
+    If this isn't given, Django will use ``app_label + '_' + module_name``.
  628
+
  629
+``exceptions``
  630
+    Names of extra exception subclasses to include in the generated module.
  631
+    These exceptions are available from instance methods and from module-level
  632
+    methods::
  633
+
  634
+        exceptions = ("DisgustingToppingsException", "BurntCrust")
  635
+
  636
+``get_latest_by``
  637
+    The name of a ``DateField`` or ``DateTimeField``. If given, the module will
  638
+    have a ``get_latest()`` function that fetches the "latest" object according
  639
+    to that field::
  640
+
  641
+        get_latest_by = "order_date"
  642
+
  643
+    See `Getting the "latest" object`_ for a full example.
  644
+
  645
+    .. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/
  646
+
  647
+``module_constants``
  648
+    A dictionary of names/values to use as extra module-level constants::
  649
+
  650
+        module_constants = {
  651
+            'MEAT_TYPE_PEPPERONI' : 1,
  652
+            'MEAT_TYPE_SAUSAGE' : 2,
  653
+        }
  654
+
  655
+``module_name``
  656
+    The name of the module::
  657
+
  658
+        module_name = "pizza_orders"
  659
+
  660
+    If this isn't given, Django will use a lowercased version of the class
  661
+    name, plus "s". This "poor man's pluralization" is intentional: Any other
  662
+    level of magic pluralization would get confusing.
  663
+
  664
+``order_with_respect_to``
  665
+    Marks this object as "orderable" with respect to the given field. This is
  666
+    almost always used with related objects to allow them to be ordered with
  667
+    respect to a parent object. For example, if a ``PizzaToppping`` relates to
  668
+    a ``Pizza`` object, you might use::
  669
+
  670
+        order_with_respect_to = 'pizza'
  671
+
  672
+    to allow the toppings to be ordered with respect to the associated pizza.
  673
+
  674
+``ordering``
  675
+    The default ordering for the object, for use by ``get_list`` and the admin::
  676
+
  677
+        ordering = ['-order_date']
  678
+
  679
+    This is a tuple or list of strings. Each string is a field name with an
  680
+    optional "-" prefix, which indicates descending order. Fields without a
  681
+    leading "-" will be ordered ascending. Use the string "?" to order randomly.
  682
+
  683
+    See `Specifying ordering`_ for a full example.
  684
+
  685
+    .. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
  686
+
  687
+``permissions``
  688
+    Extra permissions to enter into the permissions table when creating this
  689
+    object. Add, delete and change permissions are automatically created for
  690
+    each object. This option specifies extra permissions::
  691
+
  692
+        permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
  693
+
  694
+    This is a list of 2-tuples of
  695
+    ``(permission_code, human_readable_permission_name)``.
  696
+
  697
+``unique_together``
  698
+    Sets of field names that, taken together, must be unique::
  699
+
  700
+        unique_together = (("driver", "restaurant"),)
  701
+
  702
+    This is a list of lists of fields that must be unique when considered
  703
+    together. It's used in the Django admin.
  704
+
  705
+``verbose_name``
  706
+    A human-readable name for the object, singular::
  707
+
  708
+        verbose_name = "pizza"
  709
+
  710
+    If this isn't given, Django will use a munged version of the class name:
  711
+    ``CamelCase`` becomes ``camel case``.
  712
+
  713
+``verbose_name_plural``
  714
+    The plural name for the object::
  715
+
  716
+        verbose_name_plural = "stories"
  717
+
  718
+    If this isn't given, Django will use ``verbose_name + "s"``.
540 719
 
541 720
 Admin options
542 721
 =============
543 722
 
544 723
 The ``admin`` field in the model tells Django how to construct the admin
545 724
 interface for the object.  The field is an instance of the ``meta.Admin``
546  
-object, which has the following options. All are optional.
  725
+object, which takes the following parameters. All are optional.
547 726
 
548 727
 ``date_hierarchy``
549 728
     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.
562 741
             multiple fields on the same line, wrap those fields in their
563 742
             own tuple.
564 743
 
565  
-            This key is required in the dict.
  744
+            This key is required in the dictionary.
566 745
 
567 746
         ``classes``
568 747
             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.
594 773
     If ``fields`` isn't given but a model does define ``admin`` as a
595 774
     ``meta.Admin`` object, Django will default to displaying each field that
596 775
     isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
597  
-    the same order as the ``fields`` in the model.
  776
+    the same order as the fields are defined in the model.
598 777
 
599 778
 ``js``
600 779
     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.
643 822
 
644 823
 ``save_as``
645 824
     Enables a "save as" feature on object pages.  Normally, objects have three
646  
-    save options: "Save", "Save and continue editing", and "Save and add
  825
+    save options: "Save", "Save and continue editing" and "Save and add
647 826
     another". If ``save_as`` is ``True``, "Save and add another" will be
648 827
     replaced by a "Save as" button.
649 828
 
@@ -674,29 +853,49 @@ of object instances. For example::
674 853
 
675 854
 Now, every ``Pizza`` object will have a ``is_disgusting()`` method.
676 855
 
677  
-There are a few object methods that have special meaning:
  856
+Note that the scope of custom methods is modified to be the same as the module
  857
+scope. These methods do NOT have access to globals within your model's module.
  858
+
  859
+See `Giving models custom methods`_ for a full example.
  860
+
  861
+.. _Giving models custom methods: http://www.djangoproject.com/documentation/models/custom_methods/
  862
+
  863
+A few object methods have special meaning:
678 864
 
679 865
 ``__repr__``
680 866
     Django uses ``repr(obj)`` in a number of places, most notably as the value
681  
-    inserted into a template when it displays an object.  Thus, you should
  867
+    inserted into a template when it displays an object. Thus, you should always
682 868
     return a nice, human-readable string for the object's ``__repr__``.
683 869
 
  870
+    Although defining ``__repr__()`` isn't required, it's strongly encouraged.
  871
+
  872
+    See `Adding __repr__()`_ for a full example.
  873
+
  874
+    .. _Adding __repr__()_: http://www.djangoproject.com/documentation/models/repr/
  875
+
684 876
 ``get_absolute_url``
685  
-    If an object defines a ``get_absolute_url`` method, it is used to
686  
-    associate a URL with an object. For example:
  877
+    Define a ``get_absolute_url`` method to tell Django how to calculate the
  878
+    URL for an object. For example::
687 879
 
688 880
         def get_absolute_url(self):
689 881
             return "/pizzas/%i/" % self.id
690 882
 
691  
-    The most useful place this is used is in the admin interface. If an object
692  
-    defines ``get_absolute_url``, the object detail page will have a "View on
693  
-    site" link that will jump you directly to the object's public view.
  883
+    Django uses this in its admin interface. If an object defines
  884
+    ``get_absolute_url``, the object detail page will have a "View on site"
  885
+    link that will jump you directly to the object's public view.
  886
+
  887
+    It's good practice to use ``get_absolute_url()`` in templates, instead of
  888
+    hard-coding your objects' URLs.
694 889
 
695 890
 ``_pre_save``
696 891
     This method is called just before an object is saved to the database. For
697 892
     example, you can use it to calculate aggregate values from other fields
698 893
     before the object is saved.
699 894
 
  895
+    See ``Adding hooks before/after saving and deleting_ for a full example.
  896
+
  897
+    .. _Adding hooks before/after saving and deleting: http://www.djangoproject.com/documentation/models/save_delete_hooks/
  898
+
700 899
 ``_post_save``
701 900
     This method is called just after the object is saved to the database. This
702 901
     could be used to update other tables, update cached information, etc.
@@ -729,16 +928,15 @@ method::
729 928
     [ ... ]
730 929
 
731 930
 Note that the scope of these methods is modified to be the same as the module
732  
-scope.
  931
+scope. These methods do NOT have access to globals within your model's module.
733 932
 
734 933
 Manipulator methods
735 934
 -------------------
736 935
 
737  
-Similarly, you can add methods to the object's manipulators (see the formfields
738  
-documentation for more on manipulators) by defining methods that being with
739  
-"_manipulator_".  This is most useful for providing custom validators for certain
740  
-fields because manipulators automatically call any method that begins with
741  
-"validate"::
  936
+Similarly, you can add methods to the object's manipulators by defining methods
  937
+that being with "_manipulator_". This is most useful for providing custom
  938
+validators for certain fields, because manipulators automatically call any
  939
+method that begins with "validate"::
742 940
 
743 941
     class Pizza(meta.Model):
744 942
         # ...
@@ -748,4 +946,4 @@ fields because manipulators automatically call any method that begins with
748 946
             from django.conf.settings import BAD_CUSTOMER_IDS
749 947
 
750 948
             if int(field_data) in BAD_CUSTOMER_IDS:
751  
-                raise validators.ValidationError("We don't deliver to this customer")
  949
+                raise validators.ValidationError, "We don't deliver to this customer."

0 notes on commit b8e1be6

Please sign in to comment.
Something went wrong with that request. Please try again.