Django

Code

root/django/branches/magic-removal/docs/model-api.txt

Revision 2800, 52.3 kB (checked in by jkocherhans, 3 years ago)

magic-removal: Fixed #1681. OneToOneField? now works properly in the admin system.

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