Django

Code

root/django/branches/queryset-refactor/docs/model-api.txt

Revision 7452, 90.7 kB (checked in by mtredinnick, 4 months ago)

queryset-refactor: Clarified what the default reverse names are for
ManyToManyFields? and ForeignKeys? on abstract base classes.

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