Django

Code

root/django/branches/0.90-bugfixes/docs/model-api.txt

Revision 1224, 45.3 kB (checked in by adrian, 3 years ago)

Fixed #121 -- Django now quotes all names in SQL queries. Also added unit tests to confirm. Thanks, Robin Munn and Sune.

Line 
1 ===============
2 Model reference
3 ===============
4
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
9 The basics:
10
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``.
14
15 A companion to this document is the `official repository of model examples`_.
16
17 .. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/
18
19 Field objects
20 =============
21
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.
26
27 In this example, there are two fields, ``first_name`` and ``last_name`` ::
28
29     class Person(meta.Model):
30         first_name = meta.CharField(maxlength=30)
31         last_name = meta.CharField(maxlength=30)
32
33 Django will use ``first_name`` and ``last_name`` as the database column names.
34
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
38 automatically create the human-readable name by using the machine-readable
39 name, converting underscores to spaces.
40
41 In this example, the human-readable name is ``"Person's first name"``::
42
43     first_name = meta.CharField("Person's first name", maxlength=30)
44
45 In this example, the human-readable name is ``"first name"``::
46
47     first_name = meta.CharField(maxlength=30)
48
49 ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
50 argument to be a model class, so use the ``verbose_name`` keyword argument to
51 specify the human-readable name::
52
53     poll = meta.ForeignKey(Poll, verbose_name="the related poll")
54     sites = meta.ManyToManyField(Site, verbose_name="list of sites")
55     place = meta.OneToOneField(Place, verbose_name="related place")
56
57 Convention is not to capitalize the first letter of the ``verbose_name``.
58 Django will automatically capitalize the first letter where it needs to.
59
60 General field options
61 ---------------------
62
63 The following arguments are available to all field types. All are optional.
64
65 ``null``
66     If ``True``, Django will store empty values as ``NULL`` in the database.
67     Default is ``False``.
68
69     Note that empty string values will always get stored as empty strings, not
70     as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
71     booleans and dates.
72
73     Avoid using ``null`` on string-based fields such as ``CharField`` and
74     ``TextField`` unless you have an excellent reason. If a string-based field
75     has ``null=True``, that means it has two possible values for "no data":
76     ``NULL``, and the empty string. In most cases, it's redundant to have two
77     possible values for "no data;" Django convention is to use the empty
78     string, not ``NULL``.
79
80 ``blank``
81     If ``True``, the field is allowed to be blank.
82
83     Note that this is different than ``null``. ``null`` is purely
84     database-related, whereas ``blank`` is validation-related. If a field has
85     ``blank=True``, validation on Django's admin site will allow entry of an
86     empty value. If a field has ``blank=False``, the field will be required.
87
88 ``choices``
89     A list of 2-tuples to use as choices for this field.
90
91     If this is given, Django's admin will use a select box instead of the
92     standard text field and will limit choices to the choices given.
93
94     A choices list looks like this::
95
96         YEAR_IN_SCHOOL_CHOICES = (
97             ('FR', 'Freshman'),
98             ('SO', 'Sophomore'),
99             ('JR', 'Junior'),
100             ('SR', 'Senior'),
101             ('GR', 'Graduate'),
102         )
103
104     The first element in each tuple is the actual value to be stored. The
105     second element is the human-readable name for the option.
106
107 ``core``
108     For objects that are edited inline to a related object.
109
110     In the Django admin, if all "core" fields in an inline-edited object are
111     cleared, the object will be deleted.
112
113     It is an error to have an inline-editable relation without at least one
114     ``core=True`` field.
115
116 ``db_column``
117     The name of the database column to use for this field. If this isn't given,
118     Django will use the field's name.
119
120     If your database column name is an SQL reserved word, or contains
121     characters that aren't allowed in Python variable names -- notably, the
122     hyphen -- that's OK. Django quotes column and table names behind the
123     scenes.
124
125 ``db_index``
126     If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
127     statement for this field.
128
129 ``default``
130     The default value for the field.
131
132 ``editable``
133     If ``False``, the field will not be editable in the admin. Default is  ``True``.
134
135 ``help_text``
136     Extra "help" text to be displayed under the field on the object's admin
137     form. It's useful for documentation even if your object doesn't have an
138     admin form.
139
140 ``primary_key``
141     If ``True``, this field is the primary key for the model.
142
143     If you don't specify ``primary_key=True`` for any fields in your model,
144     Django will automatically add this field::
145
146         id = meta.AutoField('ID', primary_key=True)
147
148     Thus, you don't need to set ``primary_key=True`` on any of your fields
149     unless you want to override the default primary-key behavior.
150
151     ``primary_key=True`` implies ``blank=False``, ``null=False`` and
152     ``unique=True``. Only one primary key is allowed on an object.
153
154 ``radio_admin``
155     By default, Django's admin uses a select-box interface (<select>) for
156     fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
157     is set to ``True``, Django will use a radio-button interface instead.
158
159     Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
160     set.
161
162 ``unique``
163     If ``True``, this field must be unique throughout the table.
164
165     This is enforced at the database level and at the Django admin-form level.
166
167 ``unique_for_date``
168     Set this to the name of a ``DateField`` or ``DateTimeField`` to require
169     that this field be unique for the value of the date field.
170
171     For example, if you have a field ``title`` that has
172     ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
173     two records with the same ``title`` and ``pub_date``.
174
175     This is enforced at the Django admin-form level but not at the database level.
176
177 ``unique_for_month``
178     Like ``unique_for_date``, but requires the field to be unique with respect
179     to the month.
180
181 ``unique_for_year``
182     Like ``unique_for_date`` and ``unique_for_month``.
183
184 ``validator_list``
185     A list of extra validators to apply to the field. Each should be a callable
186     that takes the parameters ``field_data, all_data`` and raises
187     ``django.core.validators.ValidationError`` for errors. (See the
188     `validator docs`_.)
189
190     Django comes with quite a few validators. They're in ``django.core.validators``.
191
192 .. _validator docs: http://www.djangoproject.com/documentation/forms/#validators
193
194 Field types
195 -----------
196
197 Each field in your model should be an instance of the appropriate ``Field``
198 class. Django uses the field class types to determine a few things:
199
200     * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
201     * The widget to use in Django's admin (e.g. ``<input type="text">``, ``<select>``).
202     * The minimal validation requirements, used in Django's admin and in manipulators.
203
204 Here are all available field types:
205
206 ``AutoField``
207     An ``IntegerField`` that automatically increments according to available
208     IDs. You usually won't need to use this directly; a primary key field will
209     automatically be added to your model if you don't specify otherwise. (See
210     ``primary_key`` in ``General field options`` above.)
211
212 ``BooleanField``
213     A true/false field.
214
215     The admin represents this as a checkbox.
216
217 ``CharField``
218     A string field, for small- to large-sized strings.
219
220     For large amounts of text, use ``TextField``.
221
222     The admin represents this as an ``<input type="text">`` (a single-line input).
223
224     ``CharField`` has an extra required argument, ``maxlength``, the maximum
225     length (in characters) of the field. The maxlength is enforced at the
226     database level and in Django's validation.
227
228 ``CommaSeparatedIntegerField``
229     A field of integers separated by commas. As in ``CharField``, the
230     ``maxlength`` argument is required.
231
232 ``DateField``
233     A date field. Has a few extra optional arguments:
234
235         ======================  ===================================================
236         Argument                Description
237         ======================  ===================================================
238         ``auto_now``            Automatically set the field to now every time the
239                                 object is saved. Useful for "last-modified"
240                                 timestamps.
241
242         ``auto_now_add``        Automatically set the field to now when the object
243                                 is first created. Useful for creation of
244                                 timestamps.
245         ======================  ===================================================
246
247     The admin represents this as an ``<input type="text">`` with a JavaScript
248     calendar and a shortcut for "Today."
249
250 ``DateTimeField``
251     A date and time field. Takes the same extra options as ``DateField``.
252
253     The admin represents this as two ``<input type="text">`` fields, with
254     JavaScript shortcuts.
255
256 ``EmailField``
257     A ``CharField`` that checks that the value is a valid e-mail address.
258     This doesn't accept ``maxlength``.
259
260 ``FileField``
261     A file-upload field.
262
263     Has an extra required argument, ``upload_to``, a local filesystem path to
264     which files should be upload. This path may contain `strftime formatting`_,
265     which will be replaced by the date/time of the file upload (so that
266     uploaded files don't fill up the given directory).
267
268     The admin represents this as an ``<input type="file">`` (a file-upload widget).
269
270     Using a ``FileField` or an ``ImageField`` (see below) in a model takes a few
271     steps:
272
273         1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
274            full path to a directory where you'd like Django to store uploaded
275            files. (For performance, these files are not stored in the database.)
276            Define ``MEDIA_URL`` as the base public URL of that directory. Make
277            sure that this directory is writable by the Web server's user
278            account.
279
280         2. Add the ``FileField`` or ``ImageField`` to your model, making sure
281            to define the ``upload_to`` option to tell Django to which
282            subdirectory of ``MEDIA_ROOT`` it should upload files.
283
284         3. All that will be stored in your database is a path to the file
285            (relative to ``MEDIA_ROOT``). You'll must likely want to use the
286            convenience ``get_<fieldname>_url`` function provided by Django. For
287            example, if your ``ImageField`` is called ``mug_shot``, you can get
288            the absolute URL to your image in a template with ``{{
289            object.get_mug_shot_url }}``.
290
291     .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
292
293 ``FilePathField``
294     A field whose choices are limited to the filenames in a certain directory
295     on the filesystem. Has three special arguments, of which the first is
296     required:
297
298         ======================  ===================================================
299         Argument                Description
300         ======================  ===================================================
301         ``path``                Required. The absolute filesystem path to a
302                                 directory from which this ``FilePathField`` should
303                                 get its choices. Example: ``"/home/images"``.
304
305         ``match``               Optional. A regular expression, as a string, that
306                                 ``FilePathField`` will use to filter filenames.
307                                 Note that the regex will be applied to the
308                                 base filename, not the full path. Example:
309                                 ``"foo.*\.txt^"``, which will match a file called
310                                 ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
311
312         ``recursive``           Optional. Either ``True`` or ``False``. Default is
313                                 ``False``. Specifies whether all subdirectories of
314                                 ``path`` should be included.
315         ======================  ===================================================
316
317     Of course, these arguments can be used together.
318
319     The one potential gotcha is that ``match`` applies to the base filename,
320     not the full path. So, this example::
321
322         FilePathField(path="/home/images", match="foo.*", recursive=True)
323
324     ...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
325     because the ``match`` applies to the base filename (``foo.gif`` and
326     ``bar.gif``).
327
328 ``FloatField``
329     A floating-point number. Has two **required** arguments:
330
331         ======================  ===================================================
332         Argument                Description
333         ======================  ===================================================
334         ``max_digits``          The maximum number of digits allowed in the number.
335
336         ``decimal_places``      The number of decimal places to store with the
337                                 number.
338         ======================  ===================================================
339
340     For example, to store numbers up to 999 with a resolution of 2 decimal places,
341     you'd use::
342
343         meta.FloatField(..., max_digits=5, decimal_places=2)
344
345     And to store numbers up to one million with a resolution of 10 decimal places::
346
347         meta.FloatField(..., max_digits=19, decimal_places=10)
348
349     The admin represents this as an ``<input type="text">`` (a single-line input).
350
351 ``ImageField``
352     Like ``FileField``, but validates that the uploaded object is a valid
353     image. Has two extra optional arguments, ``height_field`` and
354     ``width_field``, which, if set, will be auto-populated with the height and
355     width of the image each time a model instance is saved.
356
357     Requires the `Python Imaging Library`_.
358
359     .. _Python Imaging Library: http://www.pythonware.com/products/pil/
360
361 ``IntegerField``
362     An integer.
363
364     The admin represents this as an ``<input type="text">`` (a single-line input).
365
366 ``IPAddressField``
367     An IP address, in string format (i.e. "24.124.1.30").
368
369     The admin represents this as an ``<input type="text">`` (a single-line input).
370
371 ``NullBooleanField``
372     Like a ``BooleanField``, but allows ``NULL`` as one of the options.  Use this
373     instead of a ``BooleanField`` with ``null=True``.
374
375     The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
376
377 ``PhoneNumberField``
378     A ``CharField`` that checks that the value is a valid U.S.A.-style phone
379     number (in the format ``XXX-XXX-XXXX``).
380
381 ``PositiveIntegerField``
382     Like an ``IntegerField``, but must be positive.
383
384 ``PositiveSmallIntegerField``
385     Like a ``PositiveIntegerField``, but only allows values under a certain
386     (database-dependent) point.
387
388 ``SlugField``
389     "Slug" is a newspaper term. A slug is a short label for something,
390     containing only letters, numbers, underscores or hyphens. They're generally
391     used in URLs.
392
393     Implies ``maxlength=50`` and ``db_index=True``.
394
395     Accepts an extra option, ``prepopulate_from``, which is a list of fields
396     from which to auto-populate the slug, via JavaScript, in the object's admin
397     form::
398
399         meta.SlugField(prepopulate_from=("pre_name", "name"))
400
401     ``prepopulate_from`` doesn't accept DateTimeFields.
402
403     The admin represents ``SlugField`` as an ``<input type="text">`` (a
404     single-line input).
405
406 ``SmallIntegerField``
407     Like an ``IntegerField``, but only allows values under a certain
408     (database-dependent) point.
409
410 ``TextField``
411     A large text field.
412
413     The admin represents this as a ``<textarea>`` (a multi-line input).
414
415 ``TimeField``
416     A time. Accepts the same auto-population options as ``DateField`` and
417     ``DateTimeField``.
418
419     The admin represents this as an ``<input type="text">`` with some
420     JavaScript shortcuts.
421
422 ``URLField``
423     A field for a URL. If the ``verify_exists`` option is ``True`` (default),
424     the URL given will be checked for existence (i.e., the URL actually loads
425     and doesn't give a 404 response).
426
427     The admin represents this as an ``<input type="text">`` (a single-line input).
428
429 ``USStateField``
430     A two-letter U.S. state abbreviation.
431
432     The admin represents this as an ``<input type="text">`` (a single-line input).
433
434 ``XMLField``
435     A ``TextField`` that checks that the value is valid XML that matches a
436     given schema. Takes one required argument, ``schema_path``, which is the
437     filesystem path to a RelaxNG_ schema against which to validate the field.
438
439     .. _RelaxNG: http://www.relaxng.org/
440
441 Relationships
442 -------------
443
444 Clearly, the power of relational databases lies in relating tables to each
445 other. Django offers ways to define the most common types of database
446 relationships: Many-to-one, many-to-many and one-to-one.
447
448 Many-to-one relationships
449 ~~~~~~~~~~~~~~~~~~~~~~~~~
450
451 To define a many-to-one relationship, use ``ForeignKey``. You use it just like
452 any other ``Field`` type: by including it as a class attribute of your model.
453
454 ``ForeignKey`` requires a positional argument: The class to which the model is
455 related.
456
457 For example, if a ``Place`` model is in a ``City`` -- that is, a ``City``
458 contains multiple places but each ``Place`` is only in one ``City`` -- here's
459 how you'd represent that::
460
461     class City(meta.Model):
462         # ...
463
464     class Place(meta.Model):
465         # ...
466         city = meta.ForeignKey(City)
467
468 To create a recursive relationship -- an object that has a many-to-one
469 relationship with itself -- use ``meta.ForeignKey("self")``.
470
471 The name of a ``ForeignKey`` (``city`` in the example above) generally should
472 be the name of the model, singular. Behind the scenes, Django appends "_id" to
473 the field name to create its database column name. But your code should never
474 have to deal with the database column name, unless you write custom SQL.
475
476 See the `Many-to-one relationship model example`_ for a full example.
477
478 .. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
479
480 ``ForeignKey`` fields take a number of extra arguments for defining how the
481 relationship should work. All are optional:
482
483     =======================  ============================================================
484     Argument                 Description
485     =======================  ============================================================
486     ``edit_inline``          If not ``False``, this related object is edited
487                              "inline" on the related object's page. This means
488                              that the object will not have its own admin
489                              interface. Use either ``meta.TABULAR`` or ``meta.STACKED``,
490                              which, respectively, designate whether the inline-editable
491                              objects are displayed as a table or as a "stack" of
492                              fieldsets.
493
494     ``limit_choices_to``     A dictionary of lookup arguments and values (see
495                              the `Database API reference`_) that limit the
496                              available admin choices for this object. Use this
497                              with ``meta.LazyDate`` to limit choices of objects
498                              by date. For example::
499
500                                 limit_choices_to = {'pub_date__lte' : meta.LazyDate()}
501
502                              only allows the choice of related objects with a
503                              ``pub_date`` before the current date/time to be
504                              chosen.
505
506                              Not compatible with ``edit_inline``.
507
508     ``max_num_in_admin``     For inline-edited objects, this is the maximum
509                              number of related objects to display in the admin.
510                              Thus, if a pizza could only have up to 10
511                              toppings, ``max_num_in_admin=10`` would ensure
512                              that a user never enters more than 10 toppings.
513
514                              Note that this doesn't ensure more than 10 related
515                              toppings ever get created. It just controls the
516                              interface.
517
518     ``min_num_in_admin``     The minimum number of related objects displayed in
519                              the admin. Normally, at the creation stage,
520                              ``num_in_admin`` inline objects are shown, and at
521                              the edit stage ``num_extra_on_change`` blank
522                              objects are shown in addition to all pre-existing
523                              related objects.  However, no fewer than
524                              ``min_num_in_admin`` related objects will ever be
525                              displayed.
526
527     ``num_extra_on_change``  The number of extra blank related-object fields to
528                              show at the change stage.
529
530     ``num_in_admin``         The default number of inline objects to display
531                              on the object page at the add stage.
532
533     ``raw_id_admin``         Only display a field for the integer to be entered
534                              instead of a drop-down menu. This is useful when
535                              related to an object type that will have too many
536                              rows to make a select box practical.
537
538                              Not used with ``edit_inline``.
539
540     ``related_name``         The name to use for the relation from the related
541                              object back to this one.  For example, when if
542                              ``Topping`` has this field::
543
544                                     meta.ForeignKey(Pizza)
545
546                              the ``related_name`` will be "topping" (taken from
547                              the class name), which will in turn give ``Pizza``
548                              the methods ``get_topping_list()`` and
549                              ``get_topping_count()``.
550
551                              If you instead were to use::
552
553                                     meta.ForeignKey(Pizza, related_name="munchie")
554
555                              then the methods would be called
556                              ``get_munchie_list()``, ``get_munchie_count()``,
557                              etc.
558
559                              This is only really useful when you have a single
560                              object that relates to the same object more than
561                              once.  For example, if a ``Story`` object has both
562                              ``primary_category`` and ``secondary_category``
563                              fields, to make sure that the ``Category`` objects
564                              have the correct methods, you'd use fields like::
565
566                                     meta.ForeignKey(Category, related_name="primary_story")
567                                     meta.ForeignKey(Category, related_name="secondary_story")
568
569                              ...which would give the ``Category`` objects
570                              methods named ``get_primary_story_list()`` and
571                              ``get_secondary_story_list()``.
572
573     ``to_field``             The field on the related object that the relation
574                              is to. By default, Django uses the primary key of
575                              the related object.
576     =======================  ============================================================
577
578 .. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
579
580 Many-to-many relationships
581 ~~~~~~~~~~~~~~~~~~~~~~~~~~
582
583 To define a many-to-one relationship, use ``ManyToManyField``. You use it just
584 like any other ``Field`` type: by including it as a class attribute of your
585 model.
586
587 ``ManyToManyField`` requires a positional argument: The class to which the
588 model is related.
589
590 For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
591 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
592 here's how you'd represent that::
593
594     class Topping(meta.Model):
595         # ...
596
597     class Pizza(meta.Model):
598         # ...
599         toppings = meta.ManyToManyField(Topping)
600
601 The name of a ``ManyToManyField`` (``toppings`` in the example above) generally
602 should be the name of the model, plural.
603
604 Behind the scenes, Django creates an intermediary join table to represent the
605 many-to-many relationship.
606
607 It doesn't matter which model gets the ``ManyToManyField``, but you only need
608 it in one of the models -- not in both.
609
610 Generally, ``ManyToManyField`` instances should go in the object that's going
611 to be edited in the admin. In the above example, ``toppings`` is in ``Pizza``
612 (rather than ``Topping`` having a ``pizzas`` ``ManyToManyField`` ) because it's
613 more natural to think about a ``Pizza`` having toppings than a topping being on
614 multiple pizzas. The way it's set up above, the ``Pizza`` admin form would let
615 users select the toppings.
616
617 See the `Many-to-many relationship model example`_ for a full example.
618
619 .. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
620
621 ``ManyToManyField`` objects take a number of extra arguments for defining how
622 the relationship should work. All are optional:
623
624     =======================  ============================================================
625     Argument                 Description
626     =======================  ============================================================
627     ``related_name``         See the description of ``related_name`` in
628                              ``ForeignKey`` above.
629
630     ``filter_interface``     Use a nifty unobtrusive Javascript "filter" interface
631                              instead of the usability-challenged ``<select multiple>``
632                              in the admin form for this object. The value should be
633                              ``meta.HORIZONTAL`` or ``meta.VERTICAL`` (i.e.
634                              should the interface be stacked horizontally or
635                              vertically).
636
637     ``limit_choices_to``     See the description under ``ForeignKey`` above.
638
639     ``singular``             The singular name of the field.  Use to name the ``get_*``
640                              methods: in the example above, Django gives the ``Pizza``
641                              objects a ``get_topping_list()`` method, where ``topping``
642                              is the default ``singular`` value derived from the lowercase
643                              version of the class being linked to.  Use the singular
644                              parameter to change this, which is if you want one model to
645                              have multiple ``ManyToMany`` relationships to another model.
646     =======================  ============================================================
647
648 One-to-one relationships
649 ~~~~~~~~~~~~~~~~~~~~~~~~
650
651 To define a one-to-one relationship, use ``OneToOneField``. You use it just
652 like any other ``Field`` type: by including it as a class attribute of your
653 model.
654
655 This is most useful on the primary key of an object when that object "extends"
656 another object in some way.
657
658 ``OneToOneField`` requires a positional argument: The class to which the
659 model is related.
660
661 For example, if you're building a database of "places", you would build pretty
662 standard stuff such as address, phone number, etc. in the database. Then, if you
663 wanted to build a database of restaurants on top of the places, instead of
664 repeating yourself and replicating those fields in the ``Restaurant`` model, you
665 could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
666 restaurant "is-a" place).
667
668 This ``OneToOneField`` will actually replace the primary key ``id`` field
669 (since one-to-one relations share the same primary key), and has a few
670 differences in the admin interface:
671
672     * No ``Place`` selection interface is displayed on ``Restaurant`` pages.
673       There will be one (and only one) ``Restaurant`` for each ``Place``.
674
675     * On the ``Restaurant`` change list, every ``Place`` -- whether it has an
676       associated ``Restaurant`` or not -- will be displayed. Adding a
677       ``Restaurant`` to a ``Place`` just means filling out the required
678       ``Restaurant`` fields.
679
680 See the `One-to-one relationship model example`_ for a full example.
681
682 .. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
683
684 META options
685 ============
686
687 Give your model metadata by using an inner ``"class META"``, like so::
688
689     class Foo(meta.Model):
690         bar = meta.CharField(maxlength=30)
691         # ...
692         class META:
693             admin = meta.Admin()
694             # ...
695
696 Model metadata is "anything that's not a field" -- ordering options, admin
697 options, etc.
698
699 Here's a list of all possible ``META`` options. No options are required. Adding
700 ``class META`` to a model is completely optional.
701
702 ``admin``
703     A ``meta.Admin`` object; see `Admin options`_. If this field is given, the
704     object will have an admin interface. If it isn't given, the object won't
705     have one.
706
707 ``db_table``
708     The name of the database table to use for the module::
709
710         db_table = "pizza_orders"
711
712     If this isn't given, Django will use ``app_label + '_' + module_name``.
713
714     If your database table name is an SQL reserved word, or contains characters
715     that aren't allowed in Python variable names -- notably, the hyphen --
716     that's OK. Django quotes column and table names behind the scenes.
717
718 ``exceptions``
719     Names of extra exception subclasses to include in the generated module.
720     These exceptions are available from instance methods and from module-level
721     methods::
722
723         exceptions = ("DisgustingToppingsException", "BurntCrust")
724
725 ``get_latest_by``
726     The name of a ``DateField`` or ``DateTimeField``. If given, the module will
727     have a ``get_latest()`` function that fetches the "latest" object according
728     to that field::
729
730         get_latest_by = "order_date"
731
732     See `Getting the "latest" object`_ for a full example.
733
734     .. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/
735
736 ``module_constants``
737     A dictionary of names/values to use as extra module-level constants::
738
739         module_constants = {
740             'MEAT_TYPE_PEPPERONI' : 1,
741             'MEAT_TYPE_SAUSAGE' : 2,
742         }
743
744 ``module_name``
745     The name of the module::
746
747         module_name = "pizza_orders"
748
749     If this isn't given, Django will use a lowercased version of the class
750     name, plus ``"s"``. This "poor man's pluralization" is intentional: Any
751     other level of magic pluralization would get confusing.
752
753 ``order_with_respect_to``
754     Marks this object as "orderable" with respect to the given field. This is
755     almost always used with related objects to allow them to be ordered with
756     respect to a parent object. For example, if a ``PizzaToppping`` relates to
757     a ``Pizza`` object, you might use::
758
759         order_with_respect_to = 'pizza'
760
761     to allow the toppings to be ordered with respect to the associated pizza.
762
763 ``ordering``
764     The default ordering for the object, for use by ``get_list`` and the admin::
765
766         ordering = ['-order_date']
767
768     This is a tuple or list of strings. Each string is a field name with an
769     optional "-" prefix, which indicates descending order. Fields without a
770     leading "-" will be ordered ascending. Use the string "?" to order randomly.
771
772     See `Specifying ordering`_ for a full example.
773
774     .. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
775
776 ``permissions``
777     Extra permissions to enter into the permissions table when creating this
778     object. Add, delete and change permissions are automatically created for
779     each object that has ``admin`` set. This example specifies an extra
780     permission, ``can_deliver_pizzas``::
781
782         permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
783
784     This is a list or tuple of 2-tuples in the format
785     ``(permission_code, human_readable_permission_name)``.
786
787 ``unique_together``
788     Sets of field names that, taken together, must be unique::
789
790         unique_together = (("driver", "restaurant"),)
791
792     This is a list of lists of fields that must be unique when considered
793     together. It's used in the Django admin and is enforced at the database
794     level (i.e., the appropriate ``UNIQUE`` statements are included in the
795     ``CREATE TABLE`` statement).
796
797 ``verbose_name``
798     A human-readable name for the object, singular::
799
800         verbose_name = "pizza"
801
802     If this isn't given, Django will use a munged version of the class name:
803     ``CamelCase`` becomes ``camel case``.
804
805 ``verbose_name_plural``
806     The plural name for the object::
807
808         verbose_name_plural = "stories"
809
810     If this isn't given, Django will use ``verbose_name + "s"``.
811
812 Admin options
813 =============
814
815 The ``admin`` field in the model tells Django how to construct the admin
816 interface for the object.  The field is an instance of the ``meta.Admin``
817 object, which takes the following parameters. All are optional.
818
819 ``date_hierarchy``
820     To allow filtering of objects in the admin by date, set ``date_hierarchy``
821     to the name of the field to filter by::
822
823         date_hierarchy = 'order_date'
824
825 ``fields``
826     A list of fieldsets to display on the admin page.  Each fieldset is a 2-tuple:
827     ``(name, field_options)``.  The ``name`` is a string to name the field set,
828     and ``field_options`` is a dictionary of information about the fields to be
829     displayed in that fieldset. This dictionary has the following keys:
830
831         ``fields``
832             A tuple of field names to display in this fieldset. To display
833             multiple fields on the same line, wrap those fields in their
834             own tuple.
835
836             This key is required in the dictionary.
837
838         ``classes``
839             Extra CSS classes to apply to the fieldset. This is a simple
840             string. You can apply multiple classes by separating them with
841             spaces.
842
843             Two useful classes defined by the default stylesheet are
844             ``collapse`` and ``wide``.  Fieldsets with the ``collapse`` style
845             will be initially collapsed in the admin and replaced with a small
846             "click to expand" link.  Fieldsets with the ``wide`` style will be
847             given extra horizontal space.
848
849     For example (taken from the ``django.contrib.flatpages`` model)::
850
851         fields = (
852             (None, {
853                 'fields': ('url', 'title', 'content', 'sites')
854             }),
855             ('Advanced options', {
856                 'classes': 'collapse',
857                 'fields' : ('enable_comments', 'registration_required', 'template_name')
858             }),
859         ),
860
861     results in an admin that looks like:
862
863         .. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png
864
865     If ``fields`` isn't given but a model does define ``admin`` as a
866     ``meta.Admin`` object, Django will default to displaying each field that
867     isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
868     the same order as the fields are defined in the model.
869
870 ``js``
871     A list of strings representing URLs of JavaScript files to link into the
872     admin screen. This can be used to tweak a given type of admin page in JS or
873     to provide "quick links" to fill in default values for certain fields.
874
875 ``list_display``
876     List of fields to display on the list page in the admin.
877
878     There are a few special cases that do other things besides displaying the
879     contents of the given fields:
880
881         * If the field given is a ``ForeignKey``, the ``repr()`` of the related
882           object will be displayed.
883
884         * ``ManyToManyField`` fields aren't supported, because that would
885           entail executing a separate SQL statement for each row in the table.
886
887         * If the field is a ``BooleanField``, a "on" or "off" icon will
888           be displayed instead of ``True`` or ``False``.
889
890         * If the field name is a method of the model, it'll be called, and the
891           output will be displayed. This method should have a
892           ``short_description`` function attribute, for use as the header for
893           the field.
894
895         * Use the string ``"__repr__"`` to output the representation of the
896           object, according to your model's ``__repr__()`` function. If you
897           don't define ``list_display``, Django will use the ``__repr__`` by
898           default.
899
900     See the example below.
901
902 ``list_filter``
903     List of fields to filter by. Each field should either be a ``BooleanField``
904     or else a field with a ``ManyToOne`` relation.
905
906     Here's an example of how ``list_display`` and ``list_filter`` work (taken
907     from the ``auth.user`` model)::
908
909         list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
910         list_filter = ('is_staff', 'is_superuser'),
911
912     This results in a admin that looks like:
913
914         .. image:: http://media.djangoproject.com/img/doc/users_changelist.png
915
916     (This example also has ``search_fields`` defined; see below).
917
918 ``list_select_related``
919     Either ``True`` or ``False``. Default is ``False``. If ``True``, the admin
920     change list page will use the ``select_related`` database-API parameter in
921     its query that retrieves the list of items.
922
923     Note that Django will use ``select_related``, regardless of this setting,
924     if one of the ``list_display`` fields is a ``ForeignKey``.
925
926 ``ordering``
927     A list or tuple (see the `META options`_, above) that gives a
928     different ordering for the admin change list. If this isn't given, the
929     model's default ordering will be used.
930
931 ``save_as``
932     Enables a "save as" feature on object pages.  Normally, objects have three
933     save options: "Save", "Save and continue editing" and "Save and add
934     another". If ``save_as`` is ``True``, "Save and add another" will be
935     replaced by a "Save as" button.
936
937     "Save as" means the object will be saved as a new object (with a new ID),
938     rather than the old object.
939
940 ``save_on_top``
941     If this option is ``True``, object pages will have the save buttons across
942     the top as well as at the bottom of the page.
943
944 ``search_fields``
945     A list of field names to provide a text search for. These fields should,
946     obviously, be some kind of text field, such as ``CharField`` or
947     ``TextField``.
948
949 Model methods
950 =============
951
952 There are a number of methods you can define on model objects to control the
953 object's behavior.  First, any methods you define will be available as methods
954 of object instances. For example::
955
956     class Pizza(meta.Model):
957         # ...
958
959         def is_disgusting(self):
960             return "anchovies" in [topping.name for topping in self.get_topping_list()]
961
962 Now, every ``Pizza`` object will have a ``is_disgusting()`` method.
963
964 Note that the scope of custom methods is modified to be the same as the module
965 scope. These methods do NOT have access to globals within your model's module.
966
967 See `Giving models custom methods`_ for a full example.
968
969 .. _Giving models custom methods: http://www.djangoproject.com/documentation/models/custom_methods/
970
971 A few object methods have special meaning:
972
973 ``__repr__``
974     Django uses ``repr(obj)`` in a number of places, most notably as the value
975     inserted into a template when it displays an object. Thus, you should always
976     return a nice, human-readable string for the object's ``__repr__``.
977
978     Although defining ``__repr__()`` isn't required, it's strongly encouraged.
979
980     See `Adding repr`_ for a full example.
981
982     .. _Adding repr: http://www.djangoproject.com/documentation/models/repr/
983
984 ``get_absolute_url``
985     Define a ``get_absolute_url`` method to tell Django how to calculate the
986     URL for an object. For example::
987
988         def get_absolute_url(self):
989             return "/pizzas/%i/" % self.id
990
991     Django uses this in its admin interface. If an object defines
992     ``get_absolute_url``, the object detail page will have a "View on site"
993     link that will jump you directly to the object's public view.
994
995     It's good practice to use ``get_absolute_url()`` in templates, instead of
996     hard-coding your objects' URLs.
997
998 ``_pre_save``
999     This method is called just before an object is saved to the database. For
1000     example, you can use it to calculate aggregate values from other fields
1001     before the object is saved.
1002
1003     See `Adding hooks before/after saving and deleting`_ for a full example.
1004
1005     .. _Adding hooks before/after saving and deleting: http://www.djangoproject.com/documentation/models/save_delete_hooks/
1006
1007 ``_post_save``
1008     This method is called just after the object is saved to the database. This
1009     could be used to update other tables, update cached information, etc.
1010
1011 ``_pre_delete``
1012     Like ``_pre_save``, but for deletion.
1013
1014 ``_post_delete``
1015     Like ``_post_save``, but for deletion.
1016
1017 Module-level methods
1018 --------------------
1019
1020 Since each data class effectively turns into a "magic" Python module under
1021 ``django.models``, there are times you'll want to write methods that live in
1022 that module.  Any model method that begins with "_module_" is turned into a
1023 module-level function::
1024
1025     class Pizza(meta.Model):
1026         # ...
1027
1028         def _module_get_pizzas_to_deliver():
1029             return get_list(delivered__exact=False)
1030
1031 This will make the top-level ``pizzas`` module have a ``get_pizzas_to_deliver()``
1032 method::
1033
1034     >>> from django.models.pizza_hut import pizzas
1035     >>> pizzas.get_pizzas_to_deliver()
1036     [ ... ]
1037
1038 Note that the scope of these methods is modified to be the same as the module
1039 scope. These methods do NOT have access