Django

Code

root/django/tags/releases/0.96/docs/model-api.txt

Revision 4804, 71.0 kB (checked in by ubernostrum, 2 years ago)

Remove notes about things added/removed in development version, since the development version is about to become 0.96

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