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