Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1732 lines (1250 sloc) 66.704 kb
acc918f @jacobian Initial import of djangobook from private SVN repo.
jacobian authored
1 ======================================
2 Appendix B: Model Definition Reference
3 ======================================
4
5 Chapter 5 explains the basics of defining models, and we use them throughout
6 the rest of the book. There is, however, a *huge* range of model options
7 available not covered elsewhere. This appendix explains each possible model
8 definition option.
9
10 Note that although these APIs are considered very stable, the Django developers
11 consistently add new shortcuts and conveniences to the model definition. It's a good
12 idea to always check the latest documentation online at
13 http://www.djangoproject.com/documentation/0.96/model-api/.
14
15 Fields
16 ======
17
18 The most important part of a model -- and the only required part of a model --
19 is the list of database fields it defines.
20
21 .. admonition:: Field Name Restrictions
22
23 Django places only two restrictions on model field names:
24
25 1. A field name cannot be a Python reserved word, because that would result
26 in a Python syntax error, for example::
27
28 class Example(models.Model):
29 pass = models.IntegerField() # 'pass' is a reserved word!
30
31 2. A field name cannot contain more than one underscore in a row, due to
32 the way Django's query lookup syntax works, for example::
33
34 class Example(models.Model):
35 foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
36
37 These limitations can be worked around, though, because your field name
38 doesn't necessarily have to match your database column name. See
39 "db_column", below. below.
40
41 SQL reserved words, such as ``join``, ``where``, or ``select``, *are* allowed
42 as model field names, because Django escapes all database table names and
43 column names in every underlying SQL query. It uses the quoting syntax of your
44 particular database engine.
45
46 Each field in your model should be an instance of the appropriate ``Field``
47 class. Django uses the field class types to determine a few things:
48
49 * The database column type (e.g., ``INTEGER``, ``VARCHAR``).
50
51 * The widget to use in Django's admin interface, if you care to use it
52 (e.g., ``<input type="text">``, ``<select>``).
53
54 * The minimal validation requirements, which are used in Django's admin interface.
55
56 A complete list of field classes follows, sorted alphabetically. Note that
57 relationship fields (``ForeignKey``, etc.) are handled in the next section.
58
59 AutoField
60 ---------
61
62 An ``IntegerField`` that automatically increments according to available IDs.
63 You usually won't need to use this directly; a primary key field will
64 automatically be added to your model if you don't specify otherwise.
65
66 BooleanField
67 ------------
68
69 A true/false field.
70
71 CharField
72 ---------
73
74 A string field, for small- to large-sized strings. For large amounts of text,
75 use ``TextField``.
76
77 ``CharField`` has an extra required argument, ``maxlength``, which is the
78 maximum length (in characters) of the field. This maximum length is enforced
79 at the database level and in Django's validation.
80
81 CommaSeparatedIntegerField
82 --------------------------
83
84 A field of integers separated by commas. As in ``CharField``, the
85 ``maxlength`` argument is required.
86
87 DateField
88 ---------
89
90 A date field. ``DateField`` has a few extra optional arguments, as shown in Table B-1.
91
92 .. table:: Table B-1. Extra DateField Options
93
94 ====================== ===================================================
95 Argument Description
96 ====================== ===================================================
97 ``auto_now`` Automatically sets the field to now every time the
98 object is saved. It's useful for "last-modified"
99 timestamps. Note that the current date is *always*
100 used; it's not just a default value that you can
101 override.
102
103 ``auto_now_add`` Automatically sets the field to now when the object
104 is first created. It's useful for creation of
105 timestamps. Note that the current date is *always*
106 used; it's not just a default value that you can
107 override.
108 ====================== ===================================================
109
110 DateTimeField
111 -------------
112
113 A date and time field. It takes the same extra options as ``DateField``.
114
115 EmailField
116 ----------
117
118 A ``CharField`` that checks that the value is a valid email address. This
119 doesn't accept ``maxlength``; its ``maxlength`` is automatically set to 75.
120
121 FileField
122 ---------
123
124 A file-upload field. It has one *required* argument, as shown in Table B-3.
125
126 .. table:: Table B-2. Extra FileField Option
127
128 ====================== ===================================================
129 Argument Description
130 ====================== ===================================================
131 ``upload_to`` A local filesystem path that will be appended to
132 your ``MEDIA_ROOT`` setting to determine the
133 output of the ``get_<fieldname>_url()`` helper
134 function
135 ====================== ===================================================
136
137 This path may contain ``strftime`` formatting (see
138 http://www.djangoproject.com/r/python/strftime/), which will be replaced by the
139 date/time of the file upload (so that uploaded files don't fill up the given
140 directory).
141
142 Using a ``FileField`` or an ``ImageField`` in a model takes a few
143 steps:
144
145 1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
146 full path to a directory where you'd like Django to store uploaded
147 files. (For performance, these files are not stored in the database.)
148 Define ``MEDIA_URL`` as the base public URL of that directory. Make
149 sure that this directory is writable by the Web server's user
150 account.
151
152 2. Add the ``FileField`` or ``ImageField`` to your model, making sure
153 to define the ``upload_to`` option to tell Django to which
154 subdirectory of ``MEDIA_ROOT`` it should upload files.
155
156 3. All that will be stored in your database is a path to the file
157 (relative to ``MEDIA_ROOT``). You'll most likely want to use the
158 convenience ``get_<fieldname>_url`` function provided by Django. For
159 example, if your ``ImageField`` is called ``mug_shot``, you can get
160 the absolute URL to your image in a template with ``{{
161 object.get_mug_shot_url }}``.
162
163 For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and
164 ``upload_to`` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'`` part of
165 ``upload_to`` is strftime formatting; ``'%Y'`` is the four-digit year,
166 ``'%m'`` is the two-digit month, and ``'%d'`` is the two-digit day. If you
167 upload a file on January 15, 2007, it will be saved in the directory
168 ``/home/media/photos/2007/01/15``.
169
170 If you want to retrieve the upload file's on-disk file name, or a URL that
171 refers to that file, or the file's size, you can use the
172 ``get_FIELD_filename()``, ``get_FIELD_url()``, and ``get_FIELD_size()`` methods. See
173 Appendix C for a complete explanation of these methods.
174
175 .. note::
176
177 Whenever you deal with uploaded files, you should pay close attention to
178 where you're uploading them and what type of files they are, to avoid
179 security holes. *Validate all uploaded files* so that you're sure the
180 files are what you think they are.
181
182 For example, if you blindly let somebody upload files, without validation,
183 to a directory that's within your Web server's document root, then
184 somebody could upload a CGI or PHP script and execute that script by
185 visiting its URL on your site. Don't let that happen!
186
187 FilePathField
188 -------------
189
190 A field whose choices are limited to the file names in a certain directory on
191 the filesystem. It has three special arguments, as shown in Table B-4.
192
193 .. table:: Table B-3. Extra FilePathField Options
194
195 ====================== ===================================================
196 Argument Description
197 ====================== ===================================================
198 ``path`` *Required*; the absolute filesystem path to a
199 directory from which this ``FilePathField`` should
200 get its choices (e.g., ``"/home/images"``).
201
202 ``match`` Optional; a regular expression, as a string, that
203 ``FilePathField`` will use to filter file names.
204 Note that the regex will be applied to the
205 base file name, not the full path (e.g.,
206 ``"foo.*\.txt^"``, which will match a file called
207 ``foo23.txt``, but not ``bar.txt`` or ``foo23.gif``).
208
209 ``recursive`` Optional; either ``True`` or ``False``. The default is
210 ``False``. It specifies whether all subdirectories of
211 ``path`` should be included.
212 ====================== ===================================================
213
214 Of course, these arguments can be used together.
215
216 The one potential gotcha is that ``match`` applies to the base file name,
217 not the full path. So, this example::
218
219 FilePathField(path="/home/images", match="foo.*", recursive=True)
220
221 will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
222 because the ``match`` applies to the base file name (``foo.gif`` and
223 ``bar.gif``).
224
225 FloatField
226 ----------
227
228 A floating-pint number, represented in Python by a ``float`` instance. It has
229 two *required* arguments, as shown in Table B-2.
230
231 .. table:: Table B-4. Extra FloatField Options
232
233 ====================== ===================================================
234 Argument Description
235 ====================== ===================================================
236 ``max_digits`` The maximum number of digits allowed in the number
237
238 ``decimal_places`` The number of decimal places to store with the
239 number
240 ====================== ===================================================
241
242 For example, to store numbers up to 999 with a resolution of two decimal places,
243 you'd use the following::
244
245 models.FloatField(..., max_digits=5, decimal_places=2)
246
247 And to store numbers up to approximately 1 billion with a resolution of ten
248 decimal places, you would use this::
249
250 models.FloatField(..., max_digits=19, decimal_places=10)
251
252 ImageField
253 ----------
254
255 Like ``FileField``, but validates that the uploaded object is a valid image.
256 It has two extra optional arguments, ``height_field`` and ``width_field``, which,
257 if set, will be autopopulated with the height and width of the image each
258 time a model instance is saved.
259
260 In addition to the special ``get_FIELD_*`` methods that are available for
261 ``FileField``, an ``ImageField`` also has ``get_FIELD_height()`` and
262 ``get_FIELD_width()`` methods. These are documented in Appendix C.
263
264 ``ImageField`` requires the Python Imaging Library
265 (http://www.pythonware.com/products/pil/).
266
267 IntegerField
268 ------------
269
270 An integer.
271
272 IPAddressField
273 --------------
274
275 An IP address, in string format (e.g., ``"24.124.1.30"``).
276
277 NullBooleanField
278 ----------------
279
280 Like a ``BooleanField``, but allows ``None``/``NULL`` as one of the options.
281 Use this instead of a ``BooleanField`` with ``null=True``.
282
283 PhoneNumberField
284 ----------------
285
286 A ``CharField`` that checks that the value is a valid U.S.-style phone
287 number (in the format ``XXX-XXX-XXXX``).
288
289 .. note::
290
291 If you need to represent a phone number from another country, check the
292 ``django.contrib.localflavor`` package to see if field definitions for
293 your country are included.
294
295 PositiveIntegerField
296 --------------------
297
298 Like an ``IntegerField``, but must be positive.
299
300 PositiveSmallIntegerField
301 -------------------------
302
303 Like a ``PositiveIntegerField``, but only allows values under a certain point.
304 The maximum value allowed by these fields is database dependent, but since
305 databases have a 2-byte small integer field, the maximum positive small
306 integer is usually 65,535.
307
308 SlugField
309 ---------
310
311 "Slug" is a newspaper term. A *slug* is a short label for something, containing
312 only letters, numbers, underscores, or hyphens. They're generally used in URLs.
313
314 Like a ``CharField``, you can specify ``maxlength``. If ``maxlength`` is not
315 specified, Django will use a default length of 50.
316
317 A ``SlugField`` implies ``db_index=True`` since slugs are primarily used for
318 database lookups.
319
320 ``SlugField`` accepts an extra option, ``prepopulate_from``, which is a list of fields
321 from which to autopopulate the slug, via JavaScript, in the object's admin
322 form::
323
324 models.SlugField(prepopulate_fpom=("pre_name", "name"))
325
326 ``prepopulate_from`` doesn't accept ``DateTimeField`` names as arguments.
327
328 SmallIntegerField
329 -----------------
330
331 Like an ``IntegerField``, but only allows values in a certain
332 database-dependent range (usually -32,768 to +32,767).
333
334 TextField
335 ---------
336
337 An unlimited-length text field.
338
339 TimeField
340 ---------
341
342 A time of day. It accepts the same autopopulation options as ``DateField`` and
343 ``DateTimeField``.
344
345 URLField
346 --------
347
348 A field for a URL. If the ``verify_exists`` option is ``True`` (the default),
349 the URL given will be checked for existence (i.e., the URL actually loads
350 and doesn't give a 404 response).
351
352 Like other character fields, ``URLField`` takes the ``maxlength`` argument. If
353 you don't specify ``maxlength``, a default of 200 is used.
354
355 USStateField
356 ------------
357
358 A two-letter U.S. state abbreviation.
359
360 .. note::
361
362 If you need to represent other countries or states, look first in the
363 ``django.contrib.localflavor`` package to see if Django already includes
364 fields for your locale.
365
366
367 XMLField
368 --------
369
370 A ``TextField`` that checks that the value is valid XML that matches a given
371 schema. It takes one required argument, ``schema_path``, which is the filesystem
372 path to a RELAX NG (http://www.relaxng.org/) schema against which to validate the field.
373
374 Requires ``jing`` (http://thaiopensource.com/relaxng/jing.html) to validate
375 the XML.
376
377 Universal Field Options
378 =======================
379
380 The following arguments are available to all field types. All are optional.
381
382 null
383 ----
384
385 If ``True``, Django will store empty values as ``NULL`` in the database.
386 The default is ``False``.
387
388 Note that empty string values will always get stored as empty strings, not as
389 ``NULL``. Only use ``null=True`` for nonstring fields such as integers,
390 Booleans, and dates. For both types of fields, you will also need to set
391 ``blank=True`` if you wish to permit empty values in forms, as the ``null``
392 parameter only affects database storage (see the following section, titled "blank").
393
394 Avoid using ``null`` on string-based fields such as ``CharField`` and
395 ``TextField`` unless you have an excellent reason. If a string-based field has
396 ``null=True``, that means it has two possible values for "no data": ``NULL``
397 and the empty string. In most cases, it's redundant to have two possible
398 values for "no data"; Django's convention is to use the empty string, not
399 ``NULL``.
400
401 blank
402 -----
403
404 If ``True``, the field is allowed to be blank. The default is ``False``.
405
406 Note that this is different from ``null``. ``null`` is purely
407 database related, whereas ``blank`` is validation related. If a field has
408 ``blank=True``, validation on Django's admin site will allow entry of an empty
409 value. If a field has ``blank=False``, the field will be required.
410
411 choices
412 -------
413
414 An iterable (e.g., a list, tuple, or other iterable Python object) of two tuples
415 to use as choices for this field.
416
417 If this is given, Django's admin interface will use a select box instead of the
418 standard text field and will limit choices to the choices given.
419
420 A choices list looks like this::
421
422 YEAR_IN_SCHOOL_CHOICES = (
423 ('FR', 'Freshman'),
424 ('SO', 'Sophomore'),
425 ('JR', 'Junior'),
426 ('SR', 'Senior'),
427 ('GR', 'Graduate'),
428 )
429
430 The first element in each tuple is the actual value to be stored. The
431 second element is the human-readable name for the option.
432
433 The choices list can be defined either as part of your model class::
434
435 class Foo(models.Model):
436 GENDER_CHOICES = (
437 ('M', 'Male'),
438 ('F', 'Female'),
439 )
440 gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
441
442 or outside your model class altogether::
443
444 GENDER_CHOICES = (
445 ('M', 'Male'),
446 ('F', 'Female'),
447 )
448 class Foo(models.Model):
449 gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
450
451 For each model field that has ``choices`` set, Django will add a method to
452 retrieve the human-readable name for the field's current value. See Appendix
453 C for more details.
454
455 db_column
456 ---------
457
458 The name of the database column to use for this field. If this isn't given,
459 Django will use the field's name. This is useful when you're defining a model
460 around a database that already exists.
461
462 If your database column name is an SQL reserved word, or if it contains characters
463 that aren't allowed in Python variable names (notably the hyphen), that's
464 OK. Django quotes column and table names behind the scenes.
465
466 db_index
467 --------
468
469 If ``True``, Django will create a database index on this column when creating
470 the table (i.e., when running ``manage.py syncdb``).
471 ta
472 default
473 -------
474
475 The default value for the field.
476
477 editable
478 --------
479
480 If ``False``, the field will not be editable in the admin interface or via form
481 processing. The default is ``True``.
482
483 help_text
484 ---------
485
486 Extra "help" text to be displayed under the field on the object's admin form.
487 It's useful for documentation even if your object doesn't have an admin form.
488
489 primary_key
490 -----------
491
492 If ``True``, this field is the primary key for the model.
493
494 If you don't specify ``primary_key=True`` for any fields in your model, Django
495 will automatically add this field::
496
497 id = models.AutoField('ID', primary_key=True)
498
499 Thus, you don't need to set ``primary_key=True`` on any of your fields unless
500 you want to override the default primary-key behavior.
501
502 ``primary_key=True`` implies ``blank=False``, ``null=False``, and
503 ``unique=True``. Only one primary key is allowed on an object.
504
505 radio_admin
506 -----------
507
508 By default, Django's admin uses a select-box interface (<select>) for fields
509 that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin`` is set to
510 ``True``, Django will use a radio-button interface instead.
511
512 Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
513 set.
514
515 unique
516 ------
517
518 If ``True``, the value for this field must be unique throughout the table.
519
520 unique_for_date
521 ---------------
522
523 Set to the name of a ``DateField`` or ``DateTimeField`` to require that
524 this field be unique for the value of the date field, for example::
525
526 class Story(models.Model):
527 pub_date = models.DateTimeField()
528 slug = models.SlugField(unique_for_date="pub_date")
529 ...
530
531 In the preceding code, Django won't allow the creation of two stories with the same
532 slug published on the same date. This differs from using a ``unique_together``
533 constraint in that only the date of the ``pub_date`` field is
534 taken into account; the time doesn't matter.
535
536 unique_for_month
537 ----------------
538
539 Like ``unique_for_date``, but requires the field to be unique with respect to
540 the month of the given field.
541
542 unique_for_year
543 ---------------
544
545 Like ``unique_for_date`` and ``unique_for_month``, but for an entire year.
546
547 verbose_name
548 ------------
549
550 Each field type, except for ``ForeignKey``, ``ManyToManyField``, and
551 ``OneToOneField``, takes an optional first positional argument -- a
552 verbose name. If the verbose name isn't given, Django will automatically create
553 it using the field's attribute name, converting underscores to spaces.
554
555 In this example, the verbose name is ``"Person's first name"``::
556
557 first_name = models.CharField("Person's first name", maxlength=30)
558
559 In this example, the verbose name is ``"first name"``::
560
561 first_name = models.CharField(maxlength=30)
562
563 ``ForeignKey``, ``ManyToManyField``, and ``OneToOneField`` require the first
564 argument to be a model class, so use the ``verbose_name`` keyword argument::
565
566 poll = models.ForeignKey(Poll, verbose_name="the related poll")
567 sites = models.ManyToManyField(Site, verbose_name="list of sites")
568 place = models.OneToOneField(Place, verbose_name="related place")
569
570 The convention is not to capitalize the first letter of the ``verbose_name``.
571 Django will automatically capitalize the first letter where it needs to.
572
573 Relationships
574 =============
575
576 Clearly, the power of relational databases lies in relating tables to each
577 other. Django offers ways to define the three most common types of database
578 relationships: many-to-one, many-to-many, and one-to-one.
579
580 However, the semantics of one-to-one relationships are being revisited as this
581 book goes to print, so they're not covered in this section. Check the online
582 documentation for the latest information.
583
584 Many-to-One Relationships
585 -------------------------
586
587 To define a many-to-one relationship, use ``ForeignKey``. You use it just like
588 any other ``Field`` type: by including it as a class attribute of your model.
589
590 ``ForeignKey`` requires a positional argument: the class to which the model is
591 related.
592
593 For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
594 ``Manufacturer`` makes multiple cars but each ``Car`` only has one
595 ``Manufacturer`` -- use the following definitions::
596
597 class Manufacturer(models.Model):
598 ...
599
600 class Car(models.Model):
601 manufacturer = models.ForeignKey(Manufacturer)
602 ...
603
604 To create a *recursive* relationship -- an object that has a many-to-one
605 relationship with itself -- use ``models.ForeignKey('self')``::
606
607 class Employee(models.Model):
608 manager = models.ForeignKey('self')
609
610 If you need to create a relationship on a model that has not yet been defined,
611 you can use the name of the model, rather than the model object itself::
612
613 class Car(models.Model):
614 manufacturer = models.ForeignKey('Manufacturer')
615 ...
616
617 class Manufacturer(models.Model):
618 ...
619
620 Note, however, that you can only use strings to refer to models in the same
621 ``models.py`` file -- you cannot use a string to reference a model in a
622 different application, or to reference a model that has been imported from
623 elsewhere.
624
625 Behind the scenes, Django appends ``"_id"`` to the field name to create its
626 database column name. In the preceding example, the database table for the ``Car``
627 model will have a ``manufacturer_id`` column. (You can change this explicitly
628 by specifying ``db_column``; see the earlier "db_column" section.) However, your code
629 should never have to deal with the database column name, unless you write
630 custom SQL. You'll always deal with the field names of your model object.
631
632 It's suggested, but not required, that the name of a ``ForeignKey`` field
633 (``manufacturer`` in the example) be the name of the model, in lowercase letters.
634 You can, of course, call the field whatever you want, for example::
635
636 class Car(models.Model):
637 company_that_makes_it = models.ForeignKey(Manufacturer)
638 # ...
639
640 ``ForeignKey`` fields take a number of extra arguments for defining how the
641 relationship should work (see Table B-5). All are optional.
642
643 .. table:: Table B-5. ForeignKey Options
644
645 ======================= ============================================================
646 Argument Description
647 ======================= ============================================================
648 ``edit_inline`` If not ``False``, this related object is edited
649 "inline" on the related object's page. This means
650 that the object will not have its own admin
651 interface. Use either ``models.TABULAR`` or ``models.STACKED``,
652 which, respectively, designate whether the inline-editable
653 objects are displayed as a table or as a "stack" of
654 fieldsets.
655
656 ``limit_choices_to`` A dictionary of lookup arguments and values (see
657 Appendix C) that limit the
658 available admin choices for this object. Use this
659 with functions from the Python ``datetime`` module
660 to limit choices of objects by date. For example, the following::
661
662 limit_choices_to = {'pub_date__lte': datetime.now}
663
664 only allows the choice of related objects with a
665 ``pub_date`` before the current date/time to be
666 chosen.
667
668 Instead of a dictionary, this can be a ``Q``
669 object (see Appendix C) for more complex queries.
670
671 This is not compatible with ``edit_inline``.
672
673 ``max_num_in_admin`` For inline-edited objects, this is the maximum
674 number of related objects to display in the admin interface.
675 Thus, if a pizza could have only up to ten
676 toppings, ``max_num_in_admin=10`` would ensure
677 that a user never enters more than ten toppings.
678
679 Note that this doesn't ensure more than ten related
680 toppings ever get created. It simply controls the
681 admin interface; it doesn't enforce things at the
682 Python API level or database level.
683
684 ``min_num_in_admin`` The minimum number of related objects displayed in
685 the admin interface. Normally, at the creation stage,
686 ``num_in_admin`` inline objects are shown, and at
687 the edit stage, ``num_extra_on_change`` blank
688 objects are shown in addition to all pre-existing
689 related objects. However, no fewer than
690 ``min_num_in_admin`` related objects will ever be
691 displayed.
692
693 ``num_extra_on_change`` The number of extra blank related-object fields to
694 show at the change stage.
695
696 ``num_in_admin`` The default number of inline objects to display
697 on the object page at the add stage.
698
699 ``raw_id_admin`` Only display a field for the integer to be entered
700 instead of a drop-down menu. This is useful when
701 related to an object type that will have too many
702 rows to make a select box practical.
703
704 This is not used with ``edit_inline``.
705
706 ``related_name`` The name to use for the relation from the related
707 object back to this one. See Appendix C for
708 more information.
709
710 ``to_field`` The field on the related object that the relation
711 is to. By default, Django uses the primary key of
712 the related object.
713 ======================= ============================================================
714
715 Many-to-Many Relationships
716 --------------------------
717
718 To define a many-to-many relationship, use ``ManyToManyField``. Like
719 ``ForeignKey``, ``ManyToManyField`` requires a positional argument: the class
720 to which the model is related.
721
722 For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
723 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
724 here's how you'd represent that::
725
726 class Topping(models.Model):
727 ...
728
729 class Pizza(models.Model):
730 toppings = models.ManyToManyField(Topping)
731 ...
732
733 As with ``ForeignKey``, a relationship to self can be defined by using the
734 string ``'self'`` instead of the model name, and you can refer to as-yet
735 undefined models by using a string containing the model name. However, you
736 can only use strings to refer to models in the same ``models.py`` file -- you
737 cannot use a string to reference a model in a different application, or to
738 reference a model that has been imported from elsewhere.
739
740 It's suggested, but not required, that the name of a ``ManyToManyField``
741 (``toppings`` in the example) be a plural term describing the set of related
742 model objects.
743
744 Behind the scenes, Django creates an intermediary join table to represent the
745 many-to-many relationship.
746
747 It doesn't matter which model gets the ``ManyToManyField``, but you need
748 it in only one of the models -- not in both.
749
750 If you're using the admin interface, ``ManyToManyField`` instances should go
751 in the object that's going to be edited in the admin interface. In the preceding example,
752 ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a ``pizzas``
753 ``ManyToManyField`` ) because it's more natural to think about a ``Pizza``
754 having toppings than a topping being on multiple pizzas. The way it's set up
755 in the example, the ``Pizza`` admin form would let users select the toppings.
756
757 ``ManyToManyField`` objects take a number of extra arguments for defining how
758 the relationship should work (see Table B-6). All are optional.
759
760 .. table:: Table B-6. ManyToManyField Options
761
762 ======================= ============================================================
763 Argument Description
764 ======================= ============================================================
765 ``related_name`` The name to use for the relation from the related
766 object back to this one. See Appendix C for
767 more information.
768
769 ``filter_interface`` Use a nifty, unobtrusive JavaScript "filter" interface
770 instead of the usability-challenged ``<select multiple>``
771 in the admin form for this object. The value should be
772 ``models.HORIZONTAL`` or ``models.VERTICAL`` (i.e.,
773 should the interface be stacked horizontally or
774 vertically).
775
776 ``limit_choices_to`` See the description under ``ForeignKey``.
777
778 ``symmetrical`` Only used in the definition of ``ManyToManyField`` on self.
779 Consider the following model::
780
781 class Person(models.Model):
782 friends = models.ManyToManyField("self")
783
784 When Django processes this model, it identifies that it has
785 a ``ManyToManyField`` on itself, and as a result, it
786 doesn't add a ``person_set`` attribute to the ``Person``
787 class. Instead, the ``ManyToManyField`` is assumed to be
788 symmetrical -- that is, if I am your friend, then you are
789 my friend.
790
791 If you do not want symmetry in ``ManyToMany`` relationships
792 with ``self``, set ``symmetrical`` to ``False``. This will
793 force Django to add the descriptor for the reverse
794 relationship, allowing ``ManyToMany`` relationships to be
795 nonsymmetrical.
796
797 ``db_table`` The name of the table to create for storing the many-to-many
798 data. If this is not provided, Django will assume a default
799 name based upon the names of the two tables being joined.
800
801 ======================= ============================================================
802
803 Model Metadata Options
804 ======================
805
806 Model-specific metadata lives in a ``class Meta`` defined in the body of your
807 model class::
808
809 class Book(models.Model):
810 title = models.CharField(maxlength=100)
811
812 class Meta:
813 # model metadata options go here
814 ...
815
816 Model metadata is "anything that's not a field," such as ordering options and so forth.
817
818 The sections that follow present a list of all possible ``Meta`` options.
819 No options are required. Adding ``class Meta`` to a model is completely optional.
820
821 db_table
822 --------
823
824 The name of the database table to use for the model.
825
826 To save you time, Django automatically derives the name of the database table
827 from the name of your model class and the application that contains it. A model's
828 database table name is constructed by joining the model's "app label" -- the
829 name you used in ``manage.py startapp`` -- to the model's class name, with an
830 underscore between them.
831
832 For example, if you have an application ``books`` (as created by
833 ``manage.py startapp books``), a model defined as ``class Book`` will have
834 a database table named ``books``.
835
836 To override the database table name, use the ``db_table`` parameter in
837 ``class Meta``::
838
839 class Book(models.Model):
840 ...
841
842 class Meta:
843 db_table = 'things_to_read'
844
845 If this isn't given, Django will use ``app_label + '_' + model_class_name``.
846 See the section "Table Names" for more information.
847
848 If your database table name is an SQL reserved word, or it contains characters
849 that aren't allowed in Python variable names (notably the hyphen), that's
850 OK. Django quotes column and table names behind the scenes.
851
852 get_latest_by
853 -------------
854
855 The name of a ``DateField`` or ``DateTimeField`` in the model. This specifies
856 the default field to use in your model ``Manager``'s ``latest()`` method.
857
858 Here's an example::
859
860 class CustomerOrder(models.Model):
861 order_date = models.DateTimeField()
862 ...
863
864 class Meta:
865 get_latest_by = "order_date"
866
867 See Appendix C for more information on the ``latest()`` method.
868
869 order_with_respect_to
870 ---------------------
871
872 Marks this object as "orderable" with respect to the given field. This is
873 almost always used with related objects to allow them to be ordered with
874 respect to a parent object. For example, if an ``Answer`` relates to a
875 ``Question`` object, and a question has more than one answer, and the order of
876 answers matters, you'd do this::
877
878 class Answer(models.Model):
879 question = models.ForeignKey(Question)
880 # ...
881
882 class Meta:
883 order_with_respect_to = 'question'
884
885 ordering
886 --------
887
888 The default ordering for the object, for use when obtaining lists of objects::
889
890 class Book(models.Model):
891 title = models.CharField(maxlength=100)
892
893 class Meta:
894 ordering = ['title']
895
896 This is a tuple or list of strings. Each string is a field name with an
897 optional ``-`` prefix, which indicates descending order. Fields without a
898 leading ``-`` will be ordered ascending. Use the string ``"?"`` to order randomly.
899
900 For example, to order by a ``title`` field in ascending order (i.e., A-Z), use this::
901
902 ordering = ['title']
903
904 To order by ``title`` in descending order (i.e., Z-A), use this::
905
906 ordering = ['-title']
907
908 To order by ``title`` in descending order, and then by ``title`` in ascending order,
909 use this::
910
911 ordering = ['-title', 'author']
912
913 Note that, regardless of how many fields are in ``ordering``, the admin
914 site uses only the first field.
915
916 permissions
917 -----------
918
919 Extra permissions to enter into the permissions table when creating this
920 object. Add, delete, and change permissions are automatically created for each
921 object that has ``admin`` set. This example specifies an extra permission,
922 ``can_deliver_pizzas``::
923
924 class Employee(models.Model):
925 ...
926
927 class Meta:
928 permissions = (
929 ("can_deliver_pizzas", "Can deliver pizzas"),
930 )
931
932 This is a list or tuple of two tuples in the format ``(permission_code,
933 human_readable_permission_name)``.
934
935 See Chapter 12 for more on permissions.
936
937 unique_together
938 ---------------
939
940 Sets of field names that, taken together, must be unique::
941
942 class Employee(models.Model):
943 department = models.ForeignKey(Department)
944 extension = models.CharField(maxlength=10)
945 ...
946
947 class Meta:
948 unique_together = [("department", "extension")]
949
950 This is a list of lists of fields that must be unique when considered
951 together. It's used in the Django admin interface and is enforced at the database level
952 (i.e., the appropriate ``UNIQUE`` statements are included in the ``CREATE
953 TABLE`` statement).
954
955 verbose_name
956 ------------
957
958 A human-readable name for the object, singular::
959
960 class CustomerOrder(models.Model):
961 order_date = models.DateTimeField()
962 ...
963
964 class Meta:
965 verbose_name = "order"
966
967 If this isn't given, Django will use a adapted version of the class name in
968 which ``CamelCase`` becomes ``camel case``.
969
970 verbose_name_plural
971 -------------------
972
973 The plural name for the object::
974
975 class Sphynx(models.Model):
976 ...
977
978 class Meta:
979 verbose_name_plural = "sphynges"
980
981 If this isn't given, Django will add an "s" to the ``verbose_name``.
982
983 Managers
984 ========
985
986 A ``Manager`` is the interface through which database query operations are
987 provided to Django models. At least one ``Manager`` exists for every model in
988 a Django application.
989
990 The way ``Manager`` classes work is documented in Appendix C. This section
991 specifically touches on model options that customize ``Manager`` behavior.
992
993 Manager Names
994 -------------
995
996 By default, Django adds a ``Manager`` with the name ``objects`` to every
997 Django model class. However, if you want to use ``objects`` as a field name,
998 or if you want to use a name other than ``objects`` for the ``Manager``, you
999 can rename it on a per-model basis. To rename the ``Manager`` for a given
1000 class, define a class attribute of type ``models.Manager()`` on that model,
1001 for example::
1002
1003 from django.db import models
1004
1005 class Person(models.Model):
1006 ...
1007
1008 people = models.Manager()
1009
1010 Using this example model, ``Person.objects`` will generate an
1011 ``AttributeError`` exception (since ``Person`` doesn't have a ``objects``
1012 attribute), but ``Person.people.all()`` will provide a list of all ``Person``
1013 objects.
1014
1015 Custom Managers
1016 ---------------
1017
1018 You can use a custom ``Manager`` in a particular model by extending the base
1019 ``Manager`` class and instantiating your custom ``Manager`` in your model.
1020
1021 There are two reasons you might want to customize a ``Manager``: to add extra
1022 ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
1023 returns.
1024
1025 Adding Extra Manager Methods
1026 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1027
1028 Adding extra ``Manager`` methods is the preferred way to add "table-level"
1029 functionality to your models. (For "row-level" functionality -- that is,
1030 functions that act on a single instance of a model object -- use model
1031 methods (see below), not custom ``Manager`` methods.)
1032
1033 A custom ``Manager`` method can return anything you want. It doesn't have to
1034 return a ``QuerySet``.
1035
1036 For example, this custom ``Manager`` offers a method ``with_counts()``, which
1037 returns a list of all ``OpinionPoll`` objects, each with an extra
1038 ``num_responses`` attribute that is the result of an aggregate query::
1039
1040 from django.db import connection
1041
1042 class PollManager(models.Manager):
1043
1044 def with_counts(self):
1045 cursor = connection.cursor()
1046 cursor.execute("""
1047 SELECT p.id, p.question, p.poll_date, COUNT(*)
1048 FROM polls_opinionpoll p, polls_response r
1049 WHERE p.id = r.poll_id
1050 GROUP BY 1, 2, 3
1051 ORDER BY 3 DESC""")
1052 result_list = []
1053 for row in cursor.fetchall():
1054 p = self.model(id=row[0], question=row[1], poll_date=row[2])
1055 p.num_responses = row[3]
1056 result_list.append(p)
1057 return result_list
1058
1059 class OpinionPoll(models.Model):
1060 question = models.CharField(maxlength=200)
1061 poll_date = models.DateField()
1062 objects = PollManager()
1063
1064 class Response(models.Model):
1065 poll = models.ForeignKey(Poll)
1066 person_name = models.CharField(maxlength=50)
1067 response = models.TextField()
1068
1069 With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return
1070 that list of ``OpinionPoll`` objects with ``num_responses`` attributes.
1071
1072 Another thing to note about this example is that ``Manager`` methods can
1073 access ``self.model`` to get the model class to which they're attached.
1074
1075 Modifying Initial Manager QuerySets
1076 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1077
1078 A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
1079 example, using this model::
1080
1081 class Book(models.Model):
1082 title = models.CharField(maxlength=100)
1083 author = models.CharField(maxlength=50)
1084
1085 the statement ``Book.objects.all()`` will return all books in the database.
1086
1087 You can override the base ``QuerySet`` by overriding the
1088 ``Manager.get_query_set()`` method. ``get_query_set()`` should return a
1089 ``QuerySet`` with the properties you require.
1090
1091 For example, the following model has *two* managers -- one that returns all
1092 objects, and one that returns only the books by Roald Dahl::
1093
1094 # First, define the Manager subclass.
1095 class DahlBookManager(models.Manager):
1096 def get_query_set(self):
1097 return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
1098
1099 # Then hook it into the Book model explicitly.
1100 class Book(models.Model):
1101 title = models.CharField(maxlength=100)
1102 author = models.CharField(maxlength=50)
1103
1104 objects = models.Manager() # The default manager.
1105 dahl_objects = DahlBookManager() # The Dahl-specific manager.
1106
1107 With this sample model, ``Book.objects.all()`` will return all books in the
1108 database, but ``Book.dahl_objects.all()`` will return only the ones written by
1109 Roald Dahl.
1110
1111 Of course, because ``get_query_set()`` returns a ``QuerySet`` object, you can
1112 use ``filter()``, ``exclude()``, and all the other ``QuerySet`` methods on it.
1113 So these statements are all legal::
1114
1115 Book.dahl_objects.all()
1116 Book.dahl_objects.filter(title='Matilda')
1117 Book.dahl_objects.count()
1118
1119 This example also points out another interesting technique: using multiple
1120 managers on the same model. You can attach as many ``Manager()`` instances to
1121 a model as you'd like. This is an easy way to define common "filters" for your
1122 models. Here's an example::
1123
1124 class MaleManager(models.Manager):
1125 def get_query_set(self):
1126 return super(MaleManager, self).get_query_set().filter(sex='M')
1127
1128 class FemaleManager(models.Manager):
1129 def get_query_set(self):
1130 return super(FemaleManager, self).get_query_set().filter(sex='F')
1131
1132 class Person(models.Model):
1133 first_name = models.CharField(maxlength=50)
1134 last_name = models.CharField(maxlength=50)
1135 sex = models.CharField(maxlength=1, choices=(('M', 'Male'), ('F', 'Female')))
1136 people = models.Manager()
1137 men = MaleManager()
1138 women = FemaleManager()
1139
1140 This example allows you to request ``Person.men.all()``,
1141 ``Person.women.all()``, and ``Person.people.all()``, yielding predictable
1142 results.
1143
1144 If you use custom ``Manager`` objects, take note that the first ``Manager``
1145 Django encounters (in order by which they're defined in the model) has a
1146 special status. Django interprets the first ``Manager`` defined in a class as
1147 the "default" ``Manager``. Certain operations -- such as Django's admin site
1148 -- use the default ``Manager`` to obtain lists of objects, so it's generally a
1149 good idea for the first ``Manager`` to be relatively unfiltered. In the last
1150 example, the ``people`` ``Manager`` is defined first -- so it's the default
1151 ``Manager``.
1152
1153 Model Methods
1154 =============
1155
1156 Define custom methods on a model to add custom "row-level" functionality to
1157 your objects. Whereas ``Manager`` methods are intended to do "tablewide"
1158 things, model methods should act on a particular model instance.
1159
1160 This is a valuable technique for keeping business logic in one place: the
1161 model. For example, this model has a few custom methods::
1162
1163 class Person(models.Model):
1164 first_name = models.CharField(maxlength=50)
1165 last_name = models.CharField(maxlength=50)
1166 birth_date = models.DateField()
1167 address = models.CharField(maxlength=100)
1168 city = models.CharField(maxlength=50)
1169 state = models.USStateField() # Yes, this is America-centric...
1170
1171 def baby_boomer_status(self):
1172 """Returns the person's baby-boomer status."""
1173 import datetime
1174 if datetime.date(1945, 8, 1) <= self.birth_date <= datetime.date(1964, 12, 31):
1175 return "Baby boomer"
1176 if self.birth_date < datetime.date(1945, 8, 1):
1177 return "Pre-boomer"
1178 return "Post-boomer"
1179
1180 def is_midwestern(self):
1181 """Returns True if this person is from the Midwest."""
1182 return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
1183
1184 @property
1185 def full_name(self):
1186 """Returns the person's full name."""
1187 return '%s %s' % (self.first_name, self.last_name)
1188
1189 The last method in this example is a *property* -- an attribute implemented by
1190 custom getter/setter user code. Properties are a nifty trick added to Python
1191 2.2; you can read more about them at
1192 http://www.python.org/download/releases/2.2/descrintro/#property.
1193
1194 There are also a handful of model methods that have "special" meaning to
1195 Python or Django. These methods are described in the sections that follow.
1196
1197 __str__
1198 -------
1199
1200 ``__str__()`` is a Python "magic method" that defines what should be returned
1201 if you call ``str()`` on the object. Django uses ``str(obj)`` (or the related
1202 function, ``unicode(obj)``, described shortly) in a number of places, most notably
1203 as the value displayed to render an object in the Django admin site and as the
1204 value inserted into a template when it displays an object. Thus, you should
1205 always return a nice, human-readable string for the object's ``__str__``.
1206 Although this isn't required, it's strongly encouraged.
1207
1208 Here's an example::
1209
1210 class Person(models.Model):
1211 first_name = models.CharField(maxlength=50)
1212 last_name = models.CharField(maxlength=50)
1213
1214 def __str__(self):
1215 return '%s %s' % (self.first_name, self.last_name)
1216
1217 get_absolute_url
1218 ----------------
1219
1220 Define a ``get_absolute_url()`` method to tell Django how to calculate the URL
1221 for an object, for example::
1222
1223 def get_absolute_url(self):
1224 return "/people/%i/" % self.id
1225
1226 Django uses this in its admin interface. If an object defines
1227 ``get_absolute_url()``, the object-editing page will have a "View on site"
1228 link that will take you directly to the object's public view, according to
1229 ``get_absolute_url()``.
1230
1231 Also, a couple of other bits of Django, such as the syndication-feed framework,
1232 use ``get_absolute_url()`` as a convenience to reward people who've defined the
1233 method.
1234
1235 It's good practice to use ``get_absolute_url()`` in templates, instead of
1236 hard-coding your objects' URLs. For example, this template code is bad::
1237
1238 <a href="/people/{{ object.id }}/">{{ object.name }}</a>
1239
1240 But this template code is good::
1241
1242 <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
1243
1244 The problem with the way we just wrote ``get_absolute_url()`` is that it
1245 slightly violates the DRY principle: the URL for this object is defined both
1246 in the URLconf file and in the model.
1247
1248 You can further decouple your models from the URLconf using the ``permalink``
1249 decorator. This decorator is passed the view function, a list of positional
1250 parameters, and (optionally) a dictionary of named parameters. Django then
1251 works out the correct full URL path using the URLconf, substituting the
1252 parameters you have given into the URL. For example, if your URLconf
1253 contained a line such as the following::
1254
1255 (r'^people/(\d+)/$', 'people.views.details'),
1256
1257 your model could have a ``get_absolute_url`` method that looked like this::
1258
1259 @models.permalink
1260 def get_absolute_url(self):
1261 return ('people.views.details', [str(self.id)])
1262
1263 Similarly, if you had a URLconf entry that looked like this::
1264
1265 (r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)
1266
1267 you could reference this using ``permalink()`` as follows::
1268
1269 @models.permalink
1270 def get_absolute_url(self):
1271 return ('archive_view', (), {
1272 'year': self.created.year,
1273 'month': self.created.month,
1274 'day': self.created.day})
1275
1276 Notice that we specify an empty sequence for the second argument in this case,
1277 because we want to pass only keyword arguments, not named arguments.
1278
1279 In this way, you're tying the model's absolute URL to the view that is used
1280 to display it, without repeating the URL information anywhere. You can still
1281 use the ``get_absolute_url`` method in templates, as before.
1282
1283 Executing Custom SQL
1284 --------------------
1285
1286 Feel free to write custom SQL statements in custom model methods and
1287 module-level methods. The object ``django.db.connection`` represents the
1288 current database connection. To use it, call ``connection.cursor()`` to get a
1289 cursor object. Then, call ``cursor.execute(sql, [params])`` to execute the SQL,
1290 and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the resulting
1291 rows::
1292
1293 def my_custom_sql(self):
1294 from django.db import connection
1295 cursor = connection.cursor()
1296 cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
1297 row = cursor.fetchone()
1298 return row
1299
1300 ``connection`` and ``cursor`` mostly implement the standard Python DB-API
1301 (http://www.python.org/peps/pep-0249.html). If you're not familiar with the
1302 Python DB-API, note that the SQL statement in ``cursor.execute()`` uses
1303 placeholders, ``"%s"``, rather than adding parameters directly within the SQL.
1304 If you use this technique, the underlying database library will automatically
1305 add quotes and escaping to your parameter(s) as necessary. (Also note that
1306 Django expects the ``"%s"`` placeholder, *not* the ``"?"`` placeholder, which
1307 is used by the SQLite Python bindings. This is for the sake of consistency and
1308 sanity.)
1309
1310 A final note: If all you want to do is use a custom ``WHERE`` clause, you can just
1311 use the ``where``, ``tables``, and ``params`` arguments to the standard lookup
1312 API. See Appendix C.
1313
1314 Overriding Default Model Methods
1315 --------------------------------
1316
1317 As explained in Appendix C, each model gets a few methods automatically
1318 -- most notably, ``save()`` and ``delete()``. You can override these methods
1319 to alter behavior.
1320
1321 A classic use-case for overriding the built-in methods is if you want something
1322 to happen whenever you save an object, for example::
1323
1324 class Blog(models.Model):
1325 name = models.CharField(maxlength=100)
1326 tagline = models.TextField()
1327
1328 def save(self):
1329 do_something()
1330 super(Blog, self).save() # Call the "real" save() method.
1331 do_something_else()
1332
1333 You can also prevent saving::
1334
1335 class Blog(models.Model):
1336 name = models.CharField(maxlength=100)
1337 tagline = models.TextField()
1338
1339 def save(self):
1340 if self.name == "Yoko Ono's blog":
1341 return # Yoko shall never have her own blog!
1342 else:
1343 super(Blog, self).save() # Call the "real" save() method
1344
1345 Admin Options
1346 =============
1347
1348 The ``Admin`` class tells Django how to display the model in the admin site.
1349
1350 The following sections present a list of all possible ``Admin`` options. None of
1351 these options is required. To use an admin interface without specifying any options, use
1352 ``pass``, like so::
1353
1354 class Admin:
1355 pass
1356
1357 Adding ``class Admin`` to a model is completely optional.
1358
1359 date_hierarchy
1360 --------------
1361
1362 Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
1363 your model, and the change list page will include a date-based navigation
1364 using that field.
1365
1366 Here's an example::
1367
1368 class CustomerOrder(models.Model):
1369 order_date = models.DateTimeField()
1370 ...
1371
1372 class Admin:
1373 date_hierarchy = "order_date"
1374
1375 fields
1376 ------
1377
1378 Set ``fields`` to control the layout of admin interface "add" and "change" pages.
1379
1380 ``fields`` is a pretty complex nested data structure best demonstrated with an example.
1381 The following is taken from the ``FlatPage`` model that's part of
1382 ``django.contrib.flatpages``::
1383
1384 class FlatPage(models.Model):
1385 ...
1386
1387 class Admin:
1388 fields = (
1389 (None, {
1390 'fields': ('url', 'title', 'content', 'sites')
1391 }),
1392 ('Advanced options', {
1393 'classes': 'collapse',
1394 'fields' : ('enable_comments', 'registration_required', 'template_name')
1395 }),
1396 )
1397
1398 Formally, ``fields`` is a list of two tuples, in which each two-tuple
1399 represents a ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a
1400 "section" of the form.)
1401
1402 The two-tuples are in the format ``(name, field_options)``, where ``name`` is a
1403 string representing the title of the fieldset and ``field_options`` is a
1404 dictionary of information about the fieldset, including a list of fields to be
1405 displayed in it.
1406
1407 If ``fields`` isn't given, Django will default to displaying each field that
1408 isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
1409 the same order as the fields are defined in the model.
1410
1411 The ``field_options`` dictionary can have the keys described in the sections that follow.
1412
1413 fields
1414 ~~~~~~
1415
1416 A tuple of field names to display in this fieldset. This key is required.
1417
1418 To display multiple fields on the same line, wrap those fields in their own
1419 tuple. In this example, the ``first_name`` and ``last_name`` fields will
1420 display on the same line::
1421
1422 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
1423
1424 classes
1425 ~~~~~~~
1426
1427 A string containing extra CSS classes to apply to the fieldset.
1428
1429 Apply multiple classes by separating them with spaces::
1430
1431 'classes': 'wide extrapretty',
1432
1433 Two useful classes defined by the default admin site stylesheet are
1434 ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will be
1435 initially collapsed in the admin site and replaced with a small "click to expand"
1436 link. Fieldsets with the ``wide`` style will be given extra horizontal space.
1437
1438 description
1439 ~~~~~~~~~~~
1440
1441 A string of optional extra text to be displayed at the top of each fieldset,
1442 under the heading of the fieldset. It's used verbatim, so you can use any HTML
1443 and you must escape any special HTML characters (such as ampersands) yourself.
1444
1445 js
1446 --
1447
1448 A list of strings representing URLs of JavaScript files to link into the admin
1449 screen via ``<script src="">`` tags. This can be used to tweak a given type of
1450 admin page in JavaScript or to provide "quick links" to fill in default values
1451 for certain fields.
1452
1453 If you use relative URLs -- that is, URLs that don't start with ``http://`` or ``/`` --
1454 then the admin site will automatically prefix these links with
1455 ``settings.ADMIN_MEDIA_PREFIX``.
1456
1457 list_display
1458 ------------
1459
1460 Set ``list_display`` to control which fields are displayed on the change list
1461 page of the admin.
1462
1463 If you don't set ``list_display``, the admin site will display a single column
1464 that displays the ``__str__()`` representation of each object.
1465
1466 Here are a few special cases to note about ``list_display``:
1467
1468 * If the field is a ``ForeignKey``, Django will display the ``__str__()``
1469 of the related object.
1470
1471 * ``ManyToManyField`` fields aren't supported, because that would entail
1472 executing a separate SQL statement for each row in the table. If you
1473 want to do this nonetheless, give your model a custom method, and add
1474 that method's name to ``list_display``. (More information on custom
1475 methods in ``list_display`` shortly.)
1476
1477 * If the field is a ``BooleanField`` or ``NullBooleanField``, Django will
1478 display a pretty "on" or "off" icon instead of ``True`` or ``False``.
1479
1480 * If the string given is a method of the model, Django will call it and
1481 display the output. This method should have a ``short_description``
1482 function attribute, for use as the header for the field.
1483
1484 Here's a full example model::
1485
1486 class Person(models.Model):
1487 name = models.CharField(maxlength=50)
1488 birthday = models.DateField()
1489
1490 class Admin:
1491 list_display = ('name', 'decade_born_in')
1492
1493 def decade_born_in(self):
1494 return self.birthday.strftime('%Y')[:3] + "0's"
1495 decade_born_in.short_description = 'Birth decade'
1496
1497 * If the string given is a method of the model, Django will HTML-escape the
1498 output by default. If you'd rather not escape the output of the method,
1499 give the method an ``allow_tags`` attribute whose value is ``True``.
1500
1501 Here's a full example model::
1502
1503 class Person(models.Model):
1504 first_name = models.CharField(maxlength=50)
1505 last_name = models.CharField(maxlength=50)
1506 color_code = models.CharField(maxlength=6)
1507
1508 class Admin:
1509 list_display = ('first_name', 'last_name', 'colored_name')
1510
1511 def colored_name(self):
1512 return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
1513 colored_name.allow_tags = True
1514
1515 * If the string given is a method of the model that returns ``True`` or ``False``,
1516 Django will display a pretty "on" or "off" icon if you give the method a
1517 ``boolean`` attribute whose value is ``True``.
1518
1519 Here's a full example model::
1520
1521 class Person(models.Model):
1522 first_name = models.CharField(maxlength=50)
1523 birthday = models.DateField()
1524
1525 class Admin:
1526 list_display = ('name', 'born_in_fifties')
1527
1528 def born_in_fifties(self):
1529 return self.birthday.strftime('%Y')[:3] == 5
1530 born_in_fifties.boolean = True
1531
1532
1533 * The ``__str__()`` methods are just as valid in ``list_display`` as any
1534 other model method, so it's perfectly OK to do this::
1535
1536 list_display = ('__str__', 'some_other_field')
1537
1538 * Usually, elements of ``list_display`` that aren't actual database fields
1539 can't be used in sorting (because Django does all the sorting at the
1540 database level).
1541
1542 However, if an element of ``list_display`` represents a certain database
1543 field, you can indicate this fact by setting the ``admin_order_field``
1544 attribute of the item, for example::
1545
1546 class Person(models.Model):
1547 first_name = models.CharField(maxlength=50)
1548 color_code = models.CharField(maxlength=6)
1549
1550 class Admin:
1551 list_display = ('first_name', 'colored_first_name')
1552
1553 def colored_first_name(self):
1554 return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
1555 colored_first_name.allow_tags = True
1556 colored_first_name.admin_order_field = 'first_name'
1557
1558 The preceding code will tell Django to order by the ``first_name`` field when
1559 trying to sort by ``colored_first_name`` in the admin site.
1560
1561 list_display_links
1562 ------------------
1563
1564 Set ``list_display_links`` to control which fields in ``list_display`` should
1565 be linked to the "change" page for an object.
1566
1567 By default, the change list page will link the first column -- the first field
1568 specified in ``list_display`` -- to the change page for each item. But
1569 ``list_display_links`` lets you change which columns are linked. Set
1570 ``list_display_links`` to a list or tuple of field names (in the same format as
1571 ``list_display``) to link.
1572
1573 ``list_display_links`` can specify one or many field names. As long as the
1574 field names appear in ``list_display``, Django doesn't care how many (or how
1575 few) fields are linked. The only requirement is that if you want to use
1576 ``list_display_links``, you must define ``list_display``.
1577
1578 In this example, the ``first_name`` and ``last_name`` fields will be linked on
1579 the change list page::
1580
1581 class Person(models.Model):
1582 ...
1583
1584 class Admin:
1585 list_display = ('first_name', 'last_name', 'birthday')
1586 list_display_links = ('first_name', 'last_name')
1587
1588 Finally, note that in order to use ``list_display_links``, you must define
1589 ``list_display``, too.
1590
1591 list_filter
1592 -----------
1593
1594 Set ``list_filter`` to activate filters in the right sidebar of the change list
1595 page of the admin interface. This should be a list of field names, and each specified
1596 field should be either a ``BooleanField``, ``DateField``, ``DateTimeField``,
1597 or ``ForeignKey``.
1598
1599 This example, taken from the ``django.contrib.auth.models.User`` model, shows
1600 how both ``list_display`` and ``list_filter`` work::
1601
1602 class User(models.Model):
1603 ...
1604
1605 class Admin:
1606 list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
1607 list_filter = ('is_staff', 'is_superuser')
1608
1609 list_per_page
1610 -------------
1611
1612 Set ``list_per_page`` to control how many items appear on each paginated admin
1613 change list page. By default, this is set to ``100``.
1614
1615 list_select_related
1616 -------------------
1617
1618 Set ``list_select_related`` to tell Django to use ``select_related()`` in
1619 retrieving the list of objects on the admin change list page. This can save
1620 you a bunch of database queries if you're using related objects in the admin
1621 change list display.
1622
1623 The value should be either ``True`` or ``False``. The default is ``False``
1624 unless one of the ``list_display`` fields is a ``ForeignKey``.
1625
1626 For more on ``select_related()``, see Appendix C.
1627
1628 ordering
1629 --------
1630
1631 Set ``ordering`` to specify how objects on the admin change list page should
1632 be ordered. This should be a list or tuple in the same format as a model's
1633 ``ordering`` parameter.
1634
1635 If this isn't provided, the Django admin interface will use the model's default
1636 ordering.
1637
1638 save_as
1639 -------
1640
1641 Set ``save_as`` to ``True`` to enable a "save as" feature on admin change
1642 forms.
1643
1644 Normally, objects have three save options: "Save," "Save and continue editing,"
1645 and "Save and add another." If ``save_as`` is ``True``, "Save and add another"
1646 will be replaced by a "Save as" button.
1647
1648 "Save as" means the object will be saved as a new object (with a new ID),
1649 rather than the old object.
1650
1651 By default, ``save_as`` is set to ``False``.
1652
1653 save_on_top
1654 -----------
1655
1656 Set ``save_on_top`` to add save buttons across the top of your admin change
1657 forms.
1658
1659 Normally, the save buttons appear only at the bottom of the forms. If you set
1660 ``save_on_top``, the buttons will appear both on the top and the bottom.
1661
1662 By default, ``save_on_top`` is set to ``False``.
1663
1664 search_fields
1665 -------------
1666
1667 Set ``search_fields`` to enable a search box on the admin change list page.
1668 This should be set to a list of field names that will be searched whenever
1669 somebody submits a search query in that text box.
1670
1671 These fields should be some kind of text field, such as ``CharField`` or
1672 ``TextField``. You can also perform a related lookup on a ``ForeignKey`` with
1673 the lookup API "follow" notation::
1674
1675 class Employee(models.Model):
1676 department = models.ForeignKey(Department)
1677 ...
1678
1679 class Admin:
1680 search_fields = ['department__name']
1681
1682 When somebody does a search in the admin search box, Django splits the search
1683 query into words and returns all objects that contain each of the words, case
1684 insensitive, where each word must be in at least one of ``search_fields``. For
1685 example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a
1686 user searches for ``john lennon``, Django will do the equivalent of this SQL
1687 ``WHERE`` clause::
1688
1689 WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
1690 AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
1691
1692 For faster and/or more restrictive searches, prefix the field name
1693 with an operator, as shown in Table B-7.
1694
1695 .. table:: Table B-7. Operators Allowed in search_fields
1696
1697 ========== =================================================================
1698 Operator Meaning
1699 ========== =================================================================
1700 ``^`` Matches the beginning of the field. For example, if
1701 ``search_fields`` is set to ``['^first_name', '^last_name']``,
1702 and a user searches for ``john lennon``, Django will do the
1703 equivalent of this SQL ``WHERE`` clause::
1704
1705 WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
1706 AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
1707
1708 This query is more efficient than the normal ``'%john%'``
1709 query, because the database only needs to check the beginning
1710 of a column's data, rather than seeking through the entire
1711 column's data. Plus, if the column has an index on it, some
1712 databases may be able to use the index for this query, even
1713 though it's a ``LIKE`` query.
1714
1715 ``=`` Matches exactly, case-insensitive. For example, if
1716 ``search_fields`` is set to ``['=first_name', '=last_name']``
1717 and a user searches for ``john lennon``, Django will do the
1718 equivalent of this SQL ``WHERE`` clause::
1719
1720 WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
1721 AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
1722
1723 Note that the query input is split by spaces, so, following
1724 this example, it's currently not possible to search for
1725 all records in which ``first_name`` is exactly ``'john
1726 winston'`` (containing a space).
1727
1728 ``@`` Performs a full-text match. This is like the default search
1729 method, but it uses an index. Currently this is available only for
1730 MySQL.
1731 ========== =================================================================
Something went wrong with that request. Please try again.