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