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