Django

Code

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

Revision 3358, 64.8 kB (checked in by adrian, 2 years ago)

Documented allow_tags attribute for admin change list methods

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