Django

Code

root/django/branches/schema-evolution-ng/docs/model-api.txt

Revision 4309, 69.0 kB (checked in by jacob, 2 years ago)

Fixed #3287: method columns in the admin changelist can now have a boolean attribute that uses the clever little checkmark icons instead of the ugly "True" or "False" strings. Thanks for the patch, xian@mintchaos.com

<
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 In the Django development version, you can specify ``maxlength``. If
366 ``maxlength`` is not specified, Django will use a default length of 50. In
367 previous Django versions, there's no way to override the length of 50.
368
369 Implies ``db_index=True``.
370
371 Accepts an extra option, ``prepopulate_from``, which is a list of fields
372 from which to auto-populate the slug, via JavaScript, in the object's admin
373 form::
374
375     models.SlugField(prepopulate_from=("pre_name", "name"))
376
377 ``prepopulate_from`` doesn't accept DateTimeFields.
378
379 The admin represents ``SlugField`` as an ``<input type="text">`` (a
380 single-line input).
381
382 ``SmallIntegerField``
383 ~~~~~~~~~~~~~~~~~~~~~
384
385 Like an ``IntegerField``, but only allows values under a certain
386 (database-dependent) point.
387
388 ``TextField``
389 ~~~~~~~~~~~~~
390
391 A large text field.
392
393 The admin represents this as a ``<textarea>`` (a multi-line input).
394
395 ``TimeField``
396 ~~~~~~~~~~~~~
397
398 A time. Accepts the same auto-population options as ``DateField`` and
399 ``DateTimeField``.
400
401 The admin represents this as an ``<input type="text">`` with some
402 JavaScript shortcuts.
403
404 ``URLField``
405 ~~~~~~~~~~~~
406
407 A field for a URL. If the ``verify_exists`` option is ``True`` (default),
408 the URL given will be checked for existence (i.e., the URL actually loads
409 and doesn't give a 404 response).
410
411 The admin represents this as an ``<input type="text">`` (a single-line input).
412
413 ``USStateField``
414 ~~~~~~~~~~~~~~~~
415
416 A two-letter U.S. state abbreviation.
417
418 The admin represents this as an ``<input type="text">`` (a single-line input).
419
420 ``XMLField``
421 ~~~~~~~~~~~~
422
423 A ``TextField`` that checks that the value is valid XML that matches a
424 given schema. Takes one required argument, ``schema_path``, which is the
425 filesystem path to a RelaxNG_ schema against which to validate the field.
426
427 .. _RelaxNG: http://www.relaxng.org/
428
429 Field options
430 -------------
431
432 The following arguments are available to all field types. All are optional.
433
434 ``null``
435 ~~~~~~~~
436
437 If ``True``, Django will store empty values as ``NULL`` in the database.
438 Default is ``False``.
439
440 Note that empty string values will always get stored as empty strings, not
441 as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
442 booleans and dates.
443
444 Avoid using ``null`` on string-based fields such as ``CharField`` and
445 ``TextField`` unless you have an excellent reason. If a string-based field
446 has ``null=True``, that means it has two possible values for "no data":
447 ``NULL``, and the empty string. In most cases, it's redundant to have two
448 possible values for "no data;" Django convention is to use the empty
449 string, not ``NULL``.
450
451 ``blank``
452 ~~~~~~~~~
453
454 If ``True``, the field is allowed to be blank.
455
456 Note that this is different than ``null``. ``null`` is purely
457 database-related, whereas ``blank`` is validation-related. If a field has
458 ``blank=True``, validation on Django's admin site will allow entry of an
459 empty value. If a field has ``blank=False``, the field will be required.
460
461 ``choices``
462 ~~~~~~~~~~~
463
464 An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
465 field.
466
467 If this is given, Django's admin will use a select box instead of the
468 standard text field and will limit choices to the choices given.
469
470 A choices list looks like this::
471
472     YEAR_IN_SCHOOL_CHOICES = (
473         ('FR', 'Freshman'),
474         ('SO', 'Sophomore'),
475         ('JR', 'Junior'),
476         ('SR', 'Senior'),
477         ('GR', 'Graduate'),
478     )
479
480 The first element in each tuple is the actual value to be stored. The
481 second element is the human-readable name for the option.
482
483 The choices list can be defined either as part of your model class::
484
485     class Foo(models.Model):
486         GENDER_CHOICES = (
487             ('M', 'Male'),
488             ('F', 'Female'),
489         )
490         gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
491
492 or outside your model class altogether::
493
494     GENDER_CHOICES = (
495         ('M', 'Male'),
496         ('F', 'Female'),
497     )
498     class Foo(models.Model):
499         gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
500
501 Finally, note that choices can be any iterable object -- not necessarily a
502 list or tuple. This lets you construct choices dynamically. But if you find
503 yourself hacking ``choices`` to be dynamic, you're probably better off using
504 a proper database table with a ``ForeignKey``. ``choices`` is meant for static
505 data that doesn't change much, if ever.
506
507 ``core``
508 ~~~~~~~~
509
510 For objects that are edited inline to a related object.
511
512 In the Django admin, if all "core" fields in an inline-edited object are
513 cleared, the object will be deleted.
514
515 It is an error to have an inline-editable relation without at least one
516 ``core=True`` field.
517
518 Please note that each field marked "core" is treated as a required field by the
519 Django admin site. Essentially, this means you should put ``core=True`` on all
520 required fields in your related object that is being edited inline.
521
522 ``db_column``
523 ~~~~~~~~~~~~~
524
525 The name of the database column to use for this field. If this isn't given,
526 Django will use the field's name.
527
528 If your database column name is an SQL reserved word, or contains
529 characters that aren't allowed in Python variable names -- notably, the
530 hyphen -- that's OK. Django quotes column and table names behind the
531 scenes.
532
533 ``db_index``
534 ~~~~~~~~~~~~
535
536 If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
537 statement for this field.
538
539 ``default``
540 ~~~~~~~~~~~
541
542 The default value for the field.
543
544 ``editable``
545 ~~~~~~~~~~~~
546
547 If ``False``, the field will not be editable in the admin or via form
548 processing using the object's ``AddManipulator`` or ``ChangeManipulator``
549 classes. Default is ``True``.
550
551 ``help_text``
552 ~~~~~~~~~~~~~
553
554 Extra "help" text to be displayed under the field on the object's admin
555 form. It's useful for documentation even if your object doesn't have an
556 admin form.
557
558 ``primary_key``
559 ~~~~~~~~~~~~~~~
560
561 If ``True``, this field is the primary key for the model.
562
563 If you don't specify ``primary_key=True`` for any fields in your model,
564 Django will automatically add this field::
565
566     id = models.AutoField('ID', primary_key=True)
567
568 Thus, you don't need to set ``primary_key=True`` on any of your fields
569 unless you want to override the default primary-key behavior.
570
571 ``primary_key=True`` implies ``blank=False``, ``null=False`` and
572 ``unique=True``. Only one primary key is allowed on an object.
573
574 ``radio_admin``
575 ~~~~~~~~~~~~~~~
576
577 By default, Django's admin uses a select-box interface (<select>) for
578 fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
579 is set to ``True``, Django will use a radio-button interface instead.
580
581 Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
582 set.
583
584 ``unique``
585 ~~~~~~~~~~
586
587 If ``True``, this field must be unique throughout the table.
588
589 This is enforced at the database level and at the Django admin-form level.
590
591 ``unique_for_date``
592 ~~~~~~~~~~~~~~~~~~~
593
594 Set this to the name of a ``DateField`` or ``DateTimeField`` to require
595 that this field be unique for the value of the date field.
596
597 For example, if you have a field ``title`` that has
598 ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
599 two records with the same ``title`` and ``pub_date``.
600
601 This is enforced at the Django admin-form level but not at the database level.
602
603 ``unique_for_month``
604 ~~~~~~~~~~~~~~~~~~~~
605
606 Like ``unique_for_date``, but requires the field to be unique with respect
607 to the month.
608
609 ``unique_for_year``
610 ~~~~~~~~~~~~~~~~~~~
611
612 Like ``unique_for_date`` and ``unique_for_month``.
613
614 ``validator_list``
615 ~~~~~~~~~~~~~~~~~~
616
617 A list of extra validators to apply to the field. Each should be a callable
618 that takes the parameters ``field_data, all_data`` and raises
619 ``django.core.validators.ValidationError`` for errors. (See the
620 `validator docs`_.)
621
622 Django comes with quite a few validators. They're in ``django.core.validators``.
623
624 .. _validator docs: http://www.djangoproject.com/documentation/forms/#validators
625
626 Verbose field names
627 -------------------
628
629 Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
630 ``OneToOneField``, takes an optional first positional argument -- a
631 verbose name. If the verbose name isn't given, Django will automatically create
632 it using the field's attribute name, converting underscores to spaces.
633
634 In this example, the verbose name is ``"Person's first name"``::
635
636     first_name = models.CharField("Person's first name", maxlength=30)
637
638 In this example, the verbose name is ``"first name"``::
639
640     first_name = models.CharField(maxlength=30)
641
642 ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
643 argument to be a model class, so use the ``verbose_name`` keyword argument::
644
645     poll = models.ForeignKey(Poll, verbose_name="the related poll")
646     sites = models.ManyToManyField(Site, verbose_name="list of sites")
647     place = models.OneToOneField(Place, verbose_name="related place")
648
649 Convention is not to capitalize the first letter of the ``verbose_name``.
650 Django will automatically capitalize the first letter where it needs to.
651
652 Relationships
653 -------------
654
655 Clearly, the power of relational databases lies in relating tables to each
656 other. Django offers ways to define the three most common types of database
657 relationships: Many-to-one, many-to-many and one-to-one.
658
659 Many-to-one relationships
660 ~~~~~~~~~~~~~~~~~~~~~~~~~
661
662 To define a many-to-one relationship, use ``ForeignKey``. You use it just like
663 any other ``Field`` type: by including it as a class attribute of your model.
664
665 ``ForeignKey`` requires a positional argument: The class to which the model is
666 related.
667
668 For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
669 ``Manufacturer`` makes multiple cars but each ``Car`` only has one
670 ``Manufacturer`` -- use the following definitions::
671
672     class Manufacturer(models.Model):
673         # ...
674
675     class Car(models.Model):
676         manufacturer = models.ForeignKey(Manufacturer)
677         # ...
678
679 To create a recursive relationship -- an object that has a many-to-one
680 relationship with itself -- use ``models.ForeignKey('self')``.
681
682 If you need to create a relationship on a model that has not yet been defined,
683 you can use the name of the model, rather than the model object itself::
684
685     class Car(models.Model):
686         manufacturer = models.ForeignKey('Manufacturer')
687         # ...
688
689     class Manufacturer(models.Model):
690         # ...
691
692 Note, however, that you can only use strings to refer to models in the same
693 models.py file -- you cannot use a string to reference a model in a different
694 application, or to reference a model that has been imported from elsewhere.
695
696 Behind the scenes, Django appends ``"_id"`` to the field name to create its
697 database column name. In the above example, the database table for the ``Car``
698 model will have a ``manufacturer_id`` column. (You can change this explicitly
699 by specifying ``db_column``; see ``db_column`` below.)  However, your code
700 should never have to deal with the database column name, unless you write
701 custom SQL. You'll always deal with the field names of your model object.
702
703 It's suggested, but not required, that the name of a ``ForeignKey`` field
704 (``manufacturer`` in the example above) be the name of the model, lowercase.
705 You can, of course, call the field whatever you want. For example::
706
707     class Car(models.Model):
708         company_that_makes_it = models.ForeignKey(Manufacturer)
709         # ...
710
711 See the `Many-to-one relationship model example`_ for a full example.
712
713 .. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
714
715 ``ForeignKey`` fields take a number of extra arguments for defining how the
716 relationship should work. All are optional:
717
718     =======================  ============================================================
719     Argument                 Description
720     =======================  ============================================================
721     ``edit_inline``          If not ``False``, this related object is edited
722                              "inline" on the related object's page. This means
723                              that the object will not have its own admin
724                              interface. Use either ``models.TABULAR`` or ``models.STACKED``,
725                              which, respectively, designate whether the inline-editable
726                              objects are displayed as a table or as a "stack" of
727                              fieldsets.
728
729     ``limit_choices_to``     A dictionary of lookup arguments and values (see
730                              the `Database API reference`_) that limit the
731                              available admin choices for this object. Use this
732                              with ``models.LazyDate`` to limit choices of objects
733                              by date. For example::
734
735                                 limit_choices_to = {'pub_date__lte': models.LazyDate()}
736
737                              only allows the choice of related objects with a
738                              ``pub_date`` before the current date/time to be
739                              chosen.
740
741                              Instead of a dictionary this can also be a ``Q`` object
742                              (an object with a ``get_sql()`` method) for more complex
743                              queries.
744
745                              Not compatible with ``edit_inline``.
746
747     ``max_num_in_admin``     For inline-edited objects, this is the maximum
748                              number of related objects to display in the admin.
749                              Thus, if a pizza could only have up to 10
750                              toppings, ``max_num_in_admin=10`` would ensure
751                              that a user never enters more than 10 toppings.
752
753                              Note that this doesn't ensure more than 10 related
754                              toppings ever get created. It simply controls the
755                              admin interface; it doesn't enforce things at the
756                              Python API level or database level.
757
758     ``min_num_in_admin``     The minimum number of related objects displayed in
759                              the admin. Normally, at the creation stage,
760                              ``num_in_admin`` inline objects are shown, and at
761                              the edit stage ``num_extra_on_change`` blank
762                              objects are shown in addition to all pre-existing
763                              related objects.  However, no fewer than
764                              ``min_num_in_admin`` related objects will ever be
765                              displayed.
766
767     ``num_extra_on_change``  The number of extra blank related-object fields to
768                              show at the change stage.
769
770     ``num_in_admin``         The default number of inline objects to display
771                              on the object page at the add stage.
772
773     ``raw_id_admin``         Only display a field for the integer to be entered
774                              instead of a drop-down menu. This is useful when
775                              related to an object type that will have too many
776                              rows to make a select box practical.
777
778                              Not used with ``edit_inline``.
779
780     ``related_name``         The name to use for the relation from the related
781                              object back to this one. See the
782                              `related objects documentation`_ for a full
783                              explanation and example.
784
785     ``to_field``             The field on the related object that the relation
786                              is to. By default, Django uses the primary key of
787                              the related object.
788     =======================  ============================================================
789
790 .. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
791 .. _related objects documentation: http://www.djangoproject.com/documentation/db_api/#related-objects
792
793 Many-to-many relationships
794 ~~~~~~~~~~~~~~~~~~~~~~~~~~
795
796 To define a many-to-many relationship, use ``ManyToManyField``. You use it just
797 like any other ``Field`` type: by including it as a class attribute of your
798 model.
799
800 ``ManyToManyField`` requires a positional argument: The class to which the
801 model is related.
802
803 For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
804 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
805 here's how you'd represent that::
806
807     class Topping(models.Model):
808         # ...
809
810     class Pizza(models.Model):
811         # ...
812         toppings = models.ManyToManyField(Topping)
813
814 As with ``ForeignKey``, a relationship to self can be defined by using the
815 string ``'self'`` instead of the model name, and you can refer to as-yet
816 undefined models by using a string containing the model name. However, you
817 can only use strings to refer to models in the same models.py file -- you
818 cannot use a string to reference a model in a different application, or to
819 reference a model that has been imported from elsewhere.
820
821 It's suggested, but not required, that the name of a ``ManyToManyField``
822 (``toppings`` in the example above) be a plural describing the set of related
823 model objects.
824
825 Behind the scenes, Django creates an intermediary join table to represent the
826 many-to-many relationship.
827
828 It doesn't matter which model gets the ``ManyToManyField``, but you only need
829 it in one of the models -- not in both.
830
831 Generally, ``ManyToManyField`` instances should go in the object that's going
832 to be edited in the admin interface, if you're using Django's admin. In the
833 above example, ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a
834 ``pizzas`` ``ManyToManyField`` ) because it's more natural to think about a
835 ``Pizza`` having toppings than a topping being on multiple pizzas. The way it's
836 set up above, the ``Pizza`` admin form would let users select the toppings.
837
838 See the `Many-to-many relationship model example`_ for a full example.
839
840 .. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
841
842 ``ManyToManyField`` objects take a number of extra arguments for defining how
843 the relationship should work. All are optional:
844
845     =======================  ============================================================
846     Argument                 Description
847     =======================  ============================================================
848     ``related_name``         See the description under ``ForeignKey`` above.
849
850     ``filter_interface``     Use a nifty unobtrusive Javascript "filter" interface
851                              instead of the usability-challenged ``<select multiple>``
852                              in the admin form for this object. The value should be
853                              ``models.HORIZONTAL`` or ``models.VERTICAL`` (i.e.
854                              should the interface be stacked horizontally or
855                              vertically).
856
857     ``limit_choices_to``     See the description under ``ForeignKey`` above.
858
859     ``symmetrical``          Only used in the definition of ManyToManyFields on self.
860                              Consider the following model:
861
862                              class Person(models.Model):
863                                  friends = models.ManyToManyField("self")
864
865                              When Django processes this model, it identifies that it has
866                              a ``ManyToManyField`` on itself, and as a result, it
867                              doesn't add a ``person_set`` attribute to the ``Person``
868                              class. Instead, the ``ManyToManyField`` is assumed to be
869                              symmetrical -- that is, if I am your friend, then you are
870                              my friend.
871
872                              If you do not want symmetry in ``ManyToMany`` relationships
873                              with ``self``, set ``symmetrical`` to ``False``. This will
874                              force Django to add the descriptor for the reverse
875                              relationship, allowing ``ManyToMany`` relationships to be
876                              non-symmetrical.
877
878     =======================  ============================================================
879
880 One-to-one relationships
881 ~~~~~~~~~~~~~~~~~~~~~~~~
882
883 The semantics of one-to-one relationships will be changing soon, so we don't
884 recommend you use them. If that doesn't scare you away, keep reading.
885
886 To define a one-to-one relationship, use ``OneToOneField``. You use it just
887 like any other ``Field`` type: by including it as a class attribute of your
888 model.
889
890 This is most useful on the primary key of an object when that object "extends"
891 another object in some way.
892
893 ``OneToOneField`` requires a positional argument: The class to which the
894 model is related.
895
896 For example, if you're building a database of "places", you would build pretty
897 standard stuff such as address, phone number, etc. in the database. Then, if you
898 wanted to build a database of restaurants on top of the places, instead of
899 repeating yourself and replicating those fields in the ``Restaurant`` model, you
900 could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
901 restaurant "is-a" place).
902
903 As with ``ForeignKey``, a relationship to self can be defined by using the
904 string ``"self"`` instead of the model name; references to as-yet undefined
905 models can be made by using a string containing the model name.
906
907 This ``OneToOneField`` will actually replace the primary key ``id`` field
908 (since one-to-one relations share the same primary key), and will be displayed
909 as a read-only field when you edit an object in the admin interface:
910
911 See the `One-to-one relationship model example`_ for a full example.
912
913 .. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
914
915 Meta options
916 ============
917
918 Give your model metadata by using an inner ``class Meta``, like so::
919
920     class Foo(models.Model):
921         bar = models.CharField(maxlength=30)
922
923         class Meta:
924             # ...
925
926 Model metadata is "anything that's not a field", such as ordering options, etc.
927
928 Here's a list of all possible ``Meta`` options. No options are required. Adding
929 ``class Meta`` to a model is completely optional.
930
931 ``db_table``
932 ------------
933
934 The name of the database table to use for the model::
935
936     db_table = 'music_album'
937
938 If this isn't given, Django will use ``app_label + '_' + model_class_name``.
939 See "Table names" below for more.
940
941 If your database table name is an SQL reserved word, or contains characters
942 that aren't allowed in Python variable names -- notably, the hyphen --
943 that's OK. Django quotes column and table names behind the scenes.
944
945 ``get_latest_by``
946 -----------------
947
948 The name of a ``DateField`` or ``DateTimeField`` in the model. This specifies
949 the default field to use in your model ``Manager``'s ``latest()`` method.
950
951 Example::
952
953     get_latest_by = "order_date"
954
955 See the `docs for latest()`_ for more.
956
957 .. _docs for latest(): http://www.djangoproject.com/documentation/db_api/#latest-field-name-none
958
959 ``order_with_respect_to``
960 -------------------------
961
962 Marks this object as "orderable" with respect to the given field. This is
963 almost always used with related objects to allow them to be ordered with
964 respect to a parent object. For example, if an ``Answer`` relates to a
965 ``Question`` object, and a question has more than one answer, and the order
966 of answers matters, you'd do this::
967
968     class Answer(models.Model):
969         question = models.ForeignKey(Question)
970         # ...
971
972         class Meta:
973             order_with_respect_to = 'question'
974
975 ``ordering``
976 ------------
977
978 The default ordering for the object, for use when obtaining lists of objects::
979
980     ordering = ['-order_date']
981
982 This is a tuple or list of strings. Each string is a field name with an
983 optional "-" prefix, which indicates descending order. Fields without a
984 leading "-" will be ordered ascending. Use the string "?" to order randomly.
985
986 For example, to order by a ``pub_date`` field ascending, use this::
987
988     ordering = ['pub_date']
989
990 To order by ``pub_date`` descending, use this::
991
992     ordering = ['-pub_date']
993
994 To order by ``pub_date`` descending, then by ``author`` ascending, use this::
995
996     ordering = ['-pub_date', 'author']
997
998 See `Specifying ordering`_ for more examples.
999
1000 Note that, regardless of how many fields are in ``ordering``, the admin
1001 site uses only the first field.
1002
1003 .. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
1004
1005 ``permissions``
1006 ---------------
1007
1008 Extra permissions to enter into the permissions table when creating this
1009 object. Add, delete and change permissions are automatically created for
1010 each object that has ``admin`` set. This example specifies an extra
1011 permission, ``can_deliver_pizzas``::
1012
1013     permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
1014
1015 This is a list or tuple of 2-tuples in the format
1016 ``(permission_code, human_readable_permission_name)``.
1017
1018 ``unique_together``
1019 -------------------
1020
1021 Sets of field names that, taken together, must be unique::
1022
1023     unique_together = (("driver", "restaurant"),)
1024
1025 This is a list of lists of fields that must be unique when considered
1026 together. It's used in the Django admin and is enforced at the database
1027 level (i.e., the appropriate ``UNIQUE`` statements are included in the
1028 ``CREATE TABLE`` statement).
1029
1030 ``verbose_name``
1031 ----------------
1032
1033 A human-readable name for the object, singular::
1034
1035     verbose_name = "pizza"
1036
1037 If this isn't given, Django will use a munged version of the class name:
1038 ``CamelCase`` becomes ``camel case``.
1039
1040 ``verbose_name_plural``
1041 -----------------------
1042
1043 The plural name for the object::
1044
1045     verbose_name_plural = "stories"
1046
1047 If this isn't given, Django will use ``verbose_name + "s"``.
1048
1049 Table names
1050 ===========
1051
1052 To save you time, Django automatically derives the name of the database table
1053 from the name of your model class and the app that contains it. A model's
1054 database table name is constructed by joining the model's "app label" -- the
1055 name you used in ``manage.py startapp`` -- to the model's class name, with an
1056 underscore between them.
1057
1058 For example, if you have an app ``bookstore`` (as created by
1059 ``manage.py startapp bookstore``), a model defined as ``class Book`` will have
1060 a database table named ``bookstore_book``.
1061
1062 To override the database table name, use the ``db_table`` parameter in
1063 ``class Meta``.
1064
1065 Automatic primary key fields
1066 ============================
1067
1068 By default, Django gives each model the following field::
1069
1070     id = models.AutoField(primary_key=True)
1071
1072 This is an auto-incrementing primary key.
1073
1074 If you'd like to specify a custom primary key, just specify ``primary_key=True``
1075 on one of your fields. If Django sees you've explicitly set ``primary_key``, it
1076 won't add the automatic ``id`` column.
1077
1078 Each model requires exactly one field to have ``primary_key=True``.
1079
1080 Admin options
1081 =============
1082
1083 If you want your model to be visible to Django's admin site, give your model an
1084 inner ``"class Admin"``, like so::
1085
1086     class Person(models.Model):
1087         first_name = models.CharField(maxlength=30)
1088         last_name = models.CharField(maxlength=30)
1089
1090         class Admin:
1091             # Admin options go here
1092             pass
1093
1094 The ``Admin`` class tells Django how to display the model in the admin site.
1095
1096 Here's a list of all possible ``Admin`` options. None of these options are
1097 required. To use an admin interface without specifying any options, use
1098 ``pass``, like so::
1099
1100     class Admin:
1101         pass
1102
1103 Adding ``class Admin`` to a model is completely optional.
1104
1105 ``date_hierarchy``
1106 ------------------
1107
1108 Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
1109 your model, and the change list page will include a date-based drilldown
1110 navigation by that field.
1111
1112 Example::
1113
1114     date_hierarchy = 'pub_date'
1115
1116 ``fields``
1117 ----------
1118
1119 Set ``fields`` to control the layout of admin "add" and "change" pages.