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.
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
15
* Metadata used for Django's admin site goes into an inner class named
17
* With all of this, Django gives you an automatically-generated
18
database-access API, which is explained in the `Database API reference`_.
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.)
24
.. _Database API reference: http://www.djangoproject.com/documentation/db_api/
25
.. _official repository of model examples: http://www.djangoproject.com/documentation/models/
30
This example model defines a ``Person``, which has a ``first_name`` and
33
from django.db import models
35
class Person(models.Model):
36
first_name = models.CharField(maxlength=30)
37
last_name = models.CharField(maxlength=30)
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.
42
The above ``Person`` model would create a database table like this::
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
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`_.
60
.. _settings file: http://www.djangoproject.com/documentation/settings/
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
71
class Musician(models.Model):
72
first_name = models.CharField(maxlength=50)
73
last_name = models.CharField(maxlength=50)
74
instrument = models.CharField(maxlength=100)
76
class Album(models.Model):
77
artist = models.ForeignKey(Musician)
78
name = models.CharField(maxlength=100)
79
release_date = models.DateField()
80
num_stars = models.IntegerField()
82
Field name restrictions
83
-----------------------
85
Django places only two restrictions on model field names:
87
1. A field name cannot be a Python reserved word, because that would result
88
in a Python syntax error. For example::
90
class Example(models.Model):
91
pass = models.IntegerField() # 'pass' is a reserved word!
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::
96
class Example(models.Model):
97
foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
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.
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.
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:
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
119
Here are all available field types:
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`_.
134
The admin represents this as a checkbox.
139
A string field, for small- to large-sized strings.
141
For large amounts of text, use ``TextField``.
143
The admin represents this as an ``<input type="text">`` (a single-line input).
145
``CharField`` has an extra required argument, ``maxlength``, the maximum length
146
(in characters) of the field. The maxlength is enforced at the database level
147
and in Django's validation.
149
``CommaSeparatedIntegerField``
150
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152
A field of integers separated by commas. As in ``CharField``, the ``maxlength``
153
argument is required.
158
A date field. Has a few extra optional arguments:
160
====================== ===================================================
162
====================== ===================================================
163
``auto_now`` Automatically set the field to now every time the
164
object is saved. Useful for "last-modified"
165
timestamps. Note that the current date is *always*
166
used; it's not just a default value that you can
169
``auto_now_add`` Automatically set the field to now when the object
170
is first created. Useful for creation of
171
timestamps. Note that the current date is *always*
172
used; it's not just a default value that you can
174
====================== ===================================================
176
The admin represents this as an ``<input type="text">`` with a JavaScript
177
calendar and a shortcut for "Today."
182
A date and time field. Takes the same extra options as ``DateField``.
184
The admin represents this as two ``<input type="text">`` fields, with
185
JavaScript shortcuts.
190
A ``CharField`` that checks that the value is a valid e-mail address.
191
This doesn't accept ``maxlength``; its ``maxlength`` is automatically set to
199
Has an extra required argument, ``upload_to``, a local filesystem path to
200
which files should be upload. This path may contain `strftime formatting`_,
201
which will be replaced by the date/time of the file upload (so that
202
uploaded files don't fill up the given directory).
204
The admin represents this as an ``<input type="file">`` (a file-upload widget).
206
Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few
209
1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
210
full path to a directory where you'd like Django to store uploaded
211
files. (For performance, these files are not stored in the database.)
212
Define ``MEDIA_URL`` as the base public URL of that directory. Make
213
sure that this directory is writable by the Web server's user
216
2. Add the ``FileField`` or ``ImageField`` to your model, making sure
217
to define the ``upload_to`` option to tell Django to which
218
subdirectory of ``MEDIA_ROOT`` it should upload files.
220
3. All that will be stored in your database is a path to the file
221
(relative to ``MEDIA_ROOT``). You'll most likely want to use the
222
convenience ``get_<fieldname>_url`` function provided by Django. For
223
example, if your ``ImageField`` is called ``mug_shot``, you can get
224
the absolute URL to your image in a template with ``{{
225
object.get_mug_shot_url }}``.
227
For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and
228
``upload_to`` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'`` part of
229
``upload_to`` is strftime formatting; ``'%Y'`` is the four-digit year,
230
``'%m'`` is the two-digit month and ``'%d'`` is the two-digit day. If you
231
upload a file on Jan. 15, 2007, it will be saved in the directory
232
``/home/media/photos/2007/01/15``.
234
Note that whenever you deal with uploaded files, you should pay close attention
235
to where you're uploading them and what type of files they are, to avoid
236
security holes. *Validate all uploaded files* so that you're sure the files are
237
what you think they are. For example, if you blindly let somebody upload files,
238
without validation, to a directory that's within your Web server's document
239
root, then somebody could upload a CGI or PHP script and execute that script by
240
visiting its URL on your site. Don't allow that.
242
.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
247
A field whose choices are limited to the filenames in a certain directory
248
on the filesystem. Has three special arguments, of which the first is
251
====================== ===================================================
253
====================== ===================================================
254
``path`` Required. The absolute filesystem path to a
255
directory from which this ``FilePathField`` should
256
get its choices. Example: ``"/home/images"``.
258
``match`` Optional. A regular expression, as a string, that
259
``FilePathField`` will use to filter filenames.
260
Note that the regex will be applied to the
261
base filename, not the full path. Example:
262
``"foo.*\.txt^"``, which will match a file called
263
``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
265
``recursive`` Optional. Either ``True`` or ``False``. Default is
266
``False``. Specifies whether all subdirectories of
267
``path`` should be included.
268
====================== ===================================================
270
Of course, these arguments can be used together.
272
The one potential gotcha is that ``match`` applies to the base filename,
273
not the full path. So, this example::
275
FilePathField(path="/home/images", match="foo.*", recursive=True)
277
...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
278
because the ``match`` applies to the base filename (``foo.gif`` and
284
A floating-point number. Has two **required** arguments:
286
====================== ===================================================
288
====================== ===================================================
289
``max_digits`` The maximum number of digits allowed in the number.
291
``decimal_places`` The number of decimal places to store with the
293
====================== ===================================================
295
For example, to store numbers up to 999 with a resolution of 2 decimal places,
298
models.FloatField(..., max_digits=5, decimal_places=2)
300
And to store numbers up to approximately one billion with a resolution of 10
303
models.FloatField(..., max_digits=19, decimal_places=10)
305
The admin represents this as an ``<input type="text">`` (a single-line input).
310
Like ``FileField``, but validates that the uploaded object is a valid
311
image. Has two extra optional arguments, ``height_field`` and
312
``width_field``, which, if set, will be auto-populated with the height and
313
width of the image each time a model instance is saved.
315
Requires the `Python Imaging Library`_.
317
.. _Python Imaging Library: http://www.pythonware.com/products/pil/
324
The admin represents this as an ``<input type="text">`` (a single-line input).
329
An IP address, in string format (i.e. "24.124.1.30").
331
The admin represents this as an ``<input type="text">`` (a single-line input).
336
Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this
337
instead of a ``BooleanField`` with ``null=True``.
339
The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
344
A ``CharField`` that checks that the value is a valid U.S.A.-style phone
345
number (in the format ``XXX-XXX-XXXX``).
347
``PositiveIntegerField``
348
~~~~~~~~~~~~~~~~~~~~~~~~
350
Like an ``IntegerField``, but must be positive.
352
``PositiveSmallIntegerField``
353
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
355
Like a ``PositiveIntegerField``, but only allows values under a certain
356
(database-dependent) point.
361
"Slug" is a newspaper term. A slug is a short label for something,
362
containing only letters, numbers, underscores or hyphens. They're generally
365
Like a CharField, you can specify ``maxlength``. If ``maxlength`` is
366
not specified, Django will use a default length of 50.
368
Implies ``db_index=True``.
370
Accepts an extra option, ``prepopulate_from``, which is a list of fields
371
from which to auto-populate the slug, via JavaScript, in the object's admin
374
models.SlugField(prepopulate_from=("pre_name", "name"))
376
``prepopulate_from`` doesn't accept DateTimeFields.
378
The admin represents ``SlugField`` as an ``<input type="text">`` (a
381
``SmallIntegerField``
382
~~~~~~~~~~~~~~~~~~~~~
384
Like an ``IntegerField``, but only allows values under a certain
385
(database-dependent) point.
392
The admin represents this as a ``<textarea>`` (a multi-line input).
397
A time. Accepts the same auto-population options as ``DateField`` and
400
The admin represents this as an ``<input type="text">`` with some
401
JavaScript shortcuts.
406
A field for a URL. If the ``verify_exists`` option is ``True`` (default),
407
the URL given will be checked for existence (i.e., the URL actually loads
408
and doesn't give a 404 response).
410
The admin represents this as an ``<input type="text">`` (a single-line input).
415
A two-letter U.S. state abbreviation.
417
The admin represents this as an ``<input type="text">`` (a single-line input).
422
A ``TextField`` that checks that the value is valid XML that matches a
423
given schema. Takes one required argument, ``schema_path``, which is the
424
filesystem path to a RelaxNG_ schema against which to validate the field.
426
.. _RelaxNG: http://www.relaxng.org/
431
The following arguments are available to all field types. All are optional.
436
If ``True``, Django will store empty values as ``NULL`` in the database.
437
Default is ``False``.
439
Note that empty string values will always get stored as empty strings, not
440
as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
443
Avoid using ``null`` on string-based fields such as ``CharField`` and
444
``TextField`` unless you have an excellent reason. If a string-based field
445
has ``null=True``, that means it has two possible values for "no data":
446
``NULL``, and the empty string. In most cases, it's redundant to have two
447
possible values for "no data;" Django convention is to use the empty
448
string, not ``NULL``.
453
If ``True``, the field is allowed to be blank.
455
Note that this is different than ``null``. ``null`` is purely
456
database-related, whereas ``blank`` is validation-related. If a field has
457
``blank=True``, validation on Django's admin site will allow entry of an
458
empty value. If a field has ``blank=False``, the field will be required.
463
An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
466
If this is given, Django's admin will use a select box instead of the
467
standard text field and will limit choices to the choices given.
469
A choices list looks like this::
471
YEAR_IN_SCHOOL_CHOICES = (
479
The first element in each tuple is the actual value to be stored. The
480
second element is the human-readable name for the option.
482
The choices list can be defined either as part of your model class::
484
class Foo(models.Model):
489
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
491
or outside your model class altogether::
497
class Foo(models.Model):
498
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
500
For each model field that has ``choices`` set, Django will add a method to
501
retrieve the human-readable name for the field's current value. See
502
`get_FOO_display`_ in the database API documentation.
504
.. _get_FOO_display: ../db_api/#get-foo-display
506
Finally, note that choices can be any iterable object -- not necessarily a
507
list or tuple. This lets you construct choices dynamically. But if you find
508
yourself hacking ``choices`` to be dynamic, you're probably better off using
509
a proper database table with a ``ForeignKey``. ``choices`` is meant for static
510
data that doesn't change much, if ever.
515
For objects that are edited inline to a related object.
517
In the Django admin, if all "core" fields in an inline-edited object are
518
cleared, the object will be deleted.
520
It is an error to have an inline-editable relation without at least one
523
Please note that each field marked "core" is treated as a required field by the
524
Django admin site. Essentially, this means you should put ``core=True`` on all
525
required fields in your related object that is being edited inline.
530
The name of the database column to use for this field. If this isn't given,
531
Django will use the field's name.
533
If your database column name is an SQL reserved word, or contains
534
characters that aren't allowed in Python variable names -- notably, the
535
hyphen -- that's OK. Django quotes column and table names behind the
541
If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
542
statement for this field.
547
The default value for the field.
552
If ``False``, the field will not be editable in the admin or via form
553
processing using the object's ``AddManipulator`` or ``ChangeManipulator``
554
classes. Default is ``True``.
559
Extra "help" text to be displayed under the field on the object's admin
560
form. It's useful for documentation even if your object doesn't have an
566
If ``True``, this field is the primary key for the model.
568
If you don't specify ``primary_key=True`` for any fields in your model,
569
Django will automatically add this field::
571
id = models.AutoField('ID', primary_key=True)
573
Thus, you don't need to set ``primary_key=True`` on any of your fields
574
unless you want to override the default primary-key behavior.
576
``primary_key=True`` implies ``blank=False``, ``null=False`` and
577
``unique=True``. Only one primary key is allowed on an object.
582
By default, Django's admin uses a select-box interface (<select>) for
583
fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
584
is set to ``True``, Django will use a radio-button interface instead.
586
Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
592
If ``True``, this field must be unique throughout the table.
594
This is enforced at the database level and at the Django admin-form level.
599
Set this to the name of a ``DateField`` or ``DateTimeField`` to require
600
that this field be unique for the value of the date field.
602
For example, if you have a field ``title`` that has
603
``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
604
two records with the same ``title`` and ``pub_date``.
606
This is enforced at the Django admin-form level but not at the database level.
611
Like ``unique_for_date``, but requires the field to be unique with respect
617
Like ``unique_for_date`` and ``unique_for_month``.
622
A list of extra validators to apply to the field. Each should be a callable
623
that takes the parameters ``field_data, all_data`` and raises
624
``django.core.validators.ValidationError`` for errors. (See the
627
Django comes with quite a few validators. They're in ``django.core.validators``.
629
.. _validator docs: http://www.djangoproject.com/documentation/forms/#validators
634
Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
635
``OneToOneField``, takes an optional first positional argument -- a
636
verbose name. If the verbose name isn't given, Django will automatically create
637
it using the field's attribute name, converting underscores to spaces.
639
In this example, the verbose name is ``"Person's first name"``::
641
first_name = models.CharField("Person's first name", maxlength=30)
643
In this example, the verbose name is ``"first name"``::
645
first_name = models.CharField(maxlength=30)
647
``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
648
argument to be a model class, so use the ``verbose_name`` keyword argument::
650
poll = models.ForeignKey(Poll, verbose_name="the related poll")
651
sites = models.ManyToManyField(Site, verbose_name="list of sites")
652
place = models.OneToOneField(Place, verbose_name="related place")
654
Convention is not to capitalize the first letter of the ``verbose_name``.
655
Django will automatically capitalize the first letter where it needs to.
660
Clearly, the power of relational databases lies in relating tables to each
661
other. Django offers ways to define the three most common types of database
662
relationships: Many-to-one, many-to-many and one-to-one.
664
Many-to-one relationships
665
~~~~~~~~~~~~~~~~~~~~~~~~~
667
To define a many-to-one relationship, use ``ForeignKey``. You use it just like
668
any other ``Field`` type: by including it as a class attribute of your model.
670
``ForeignKey`` requires a positional argument: The class to which the model is
673
For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
674
``Manufacturer`` makes multiple cars but each ``Car`` only has one
675
``Manufacturer`` -- use the following definitions::
677
class Manufacturer(models.Model):
680
class Car(models.Model):
681
manufacturer = models.ForeignKey(Manufacturer)
684
To create a recursive relationship -- an object that has a many-to-one
685
relationship with itself -- use ``models.ForeignKey('self')``.
687
If you need to create a relationship on a model that has not yet been defined,
688
you can use the name of the model, rather than the model object itself::
690
class Car(models.Model):
691
manufacturer = models.ForeignKey('Manufacturer')
694
class Manufacturer(models.Model):
697
Note, however, that you can only use strings to refer to models in the same
698
models.py file -- you cannot use a string to reference a model in a different
699
application, or to reference a model that has been imported from elsewhere.
701
Behind the scenes, Django appends ``"_id"`` to the field name to create its
702
database column name. In the above example, the database table for the ``Car``
703
model will have a ``manufacturer_id`` column. (You can change this explicitly
704
by specifying ``db_column``; see ``db_column`` below.) However, your code
705
should never have to deal with the database column name, unless you write
706
custom SQL. You'll always deal with the field names of your model object.
708
It's suggested, but not required, that the name of a ``ForeignKey`` field
709
(``manufacturer`` in the example above) be the name of the model, lowercase.
710
You can, of course, call the field whatever you want. For example::
712
class Car(models.Model):
713
company_that_makes_it = models.ForeignKey(Manufacturer)
716
See the `Many-to-one relationship model example`_ for a full example.
718
.. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
720
``ForeignKey`` fields take a number of extra arguments for defining how the
721
relationship should work. All are optional:
723
======================= ============================================================
725
======================= ============================================================
726
``edit_inline`` If not ``False``, this related object is edited
727
"inline" on the related object's page. This means
728
that the object will not have its own admin
729
interface. Use either ``models.TABULAR`` or ``models.STACKED``,
730
which, respectively, designate whether the inline-editable
731
objects are displayed as a table or as a "stack" of
734
``limit_choices_to`` A dictionary of lookup arguments and values (see
735
the `Database API reference`_) that limit the
736
available admin choices for this object. Use this
737
with ``models.LazyDate`` to limit choices of objects
738
by date. For example::
740
limit_choices_to = {'pub_date__lte': models.LazyDate()}
742
only allows the choice of related objects with a
743
``pub_date`` before the current date/time to be
746
Instead of a dictionary this can also be a ``Q`` object
747
(an object with a ``get_sql()`` method) for more complex
750
Not compatible with ``edit_inline``.
752
``max_num_in_admin`` For inline-edited objects, this is the maximum
753
number of related objects to display in the admin.
754
Thus, if a pizza could only have up to 10
755
toppings, ``max_num_in_admin=10`` would ensure
756
that a user never enters more than 10 toppings.
758
Note that this doesn't ensure more than 10 related
759
toppings ever get created. It simply controls the
760
admin interface; it doesn't enforce things at the
761
Python API level or database level.
763
``min_num_in_admin`` The minimum number of related objects displayed in
764
the admin. Normally, at the creation stage,
765
``num_in_admin`` inline objects are shown, and at
766
the edit stage ``num_extra_on_change`` blank
767
objects are shown in addition to all pre-existing
768
related objects. However, no fewer than
769
``min_num_in_admin`` related objects will ever be
772
``num_extra_on_change`` The number of extra blank related-object fields to
773
show at the change stage.
775
``num_in_admin`` The default number of inline objects to display
776
on the object page at the add stage.
778
``raw_id_admin`` Only display a field for the integer to be entered
779
instead of a drop-down menu. This is useful when
780
related to an object type that will have too many
781
rows to make a select box practical.
783
Not used with ``edit_inline``.
785
``related_name`` The name to use for the relation from the related
786
object back to this one. See the
787
`related objects documentation`_ for a full
788
explanation and example.
790
``to_field`` The field on the related object that the relation
791
is to. By default, Django uses the primary key of
793
======================= ============================================================
795
.. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
796
.. _related objects documentation: http://www.djangoproject.com/documentation/db_api/#related-objects
798
Many-to-many relationships
799
~~~~~~~~~~~~~~~~~~~~~~~~~~
801
To define a many-to-many relationship, use ``ManyToManyField``. You use it just
802
like any other ``Field`` type: by including it as a class attribute of your
805
``ManyToManyField`` requires a positional argument: The class to which the
808
For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
809
``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
810
here's how you'd represent that::
812
class Topping(models.Model):
815
class Pizza(models.Model):
817
toppings = models.ManyToManyField(Topping)
819
As with ``ForeignKey``, a relationship to self can be defined by using the
820
string ``'self'`` instead of the model name, and you can refer to as-yet
821
undefined models by using a string containing the model name. However, you
822
can only use strings to refer to models in the same models.py file -- you
823
cannot use a string to reference a model in a different application, or to
824
reference a model that has been imported from elsewhere.
826
It's suggested, but not required, that the name of a ``ManyToManyField``
827
(``toppings`` in the example above) be a plural describing the set of related
830
Behind the scenes, Django creates an intermediary join table to represent the
831
many-to-many relationship.
833
It doesn't matter which model gets the ``ManyToManyField``, but you only need
834
it in one of the models -- not in both.
836
Generally, ``ManyToManyField`` instances should go in the object that's going
837
to be edited in the admin interface, if you're using Django's admin. In the
838
above example, ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a
839
``pizzas`` ``ManyToManyField`` ) because it's more natural to think about a
840
``Pizza`` having toppings than a topping being on multiple pizzas. The way it's
841
set up above, the ``Pizza`` admin form would let users select the toppings.
843
See the `Many-to-many relationship model example`_ for a full example.
845
.. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
847
``ManyToManyField`` objects take a number of extra arguments for defining how
848
the relationship should work. All are optional:
850
======================= ============================================================
852
======================= ============================================================
853
``related_name`` See the description under ``ForeignKey`` above.
855
``filter_interface`` Use a nifty unobtrusive Javascript "filter" interface
856
instead of the usability-challenged ``<select multiple>``
857
in the admin form for this object. The value should be
858
``models.HORIZONTAL`` or ``models.VERTICAL`` (i.e.
859
should the interface be stacked horizontally or
862
``limit_choices_to`` See the description under ``ForeignKey`` above.
864
``symmetrical`` Only used in the definition of ManyToManyFields on self.
865
Consider the following model:
867
class Person(models.Model):
868
friends = models.ManyToManyField("self")
870
When Django processes this model, it identifies that it has
871
a ``ManyToManyField`` on itself, and as a result, it
872
doesn't add a ``person_set`` attribute to the ``Person``
873
class. Instead, the ``ManyToManyField`` is assumed to be
874
symmetrical -- that is, if I am your friend, then you are
877
If you do not want symmetry in ``ManyToMany`` relationships
878
with ``self``, set ``symmetrical`` to ``False``. This will
879
force Django to add the descriptor for the reverse
880
relationship, allowing ``ManyToMany`` relationships to be
883
``db_table`` The name of the table to create for storing the many-to-many
884
data. If this is not provided, Django will assume a default
885
name based upon the names of the two tables being joined.
887
======================= ============================================================
889
One-to-one relationships
890
~~~~~~~~~~~~~~~~~~~~~~~~
892
The semantics of one-to-one relationships will be changing soon, so we don't
893
recommend you use them. If that doesn't scare you away, keep reading.
895
To define a one-to-one relationship, use ``OneToOneField``. You use it just
896
like any other ``Field`` type: by including it as a class attribute of your
899
This is most useful on the primary key of an object when that object "extends"
900
another object in some way.
902
``OneToOneField`` requires a positional argument: The class to which the
905
For example, if you're building a database of "places", you would build pretty
906
standard stuff such as address, phone number, etc. in the database. Then, if you
907
wanted to build a database of restaurants on top of the places, instead of
908
repeating yourself and replicating those fields in the ``Restaurant`` model, you
909
could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
910
restaurant "is-a" place).
912
As with ``ForeignKey``, a relationship to self can be defined by using the
913
string ``"self"`` instead of the model name; references to as-yet undefined
914
models can be made by using a string containing the model name.
916
This ``OneToOneField`` will actually replace the primary key ``id`` field
917
(since one-to-one relations share the same primary key), and will be displayed
918
as a read-only field when you edit an object in the admin interface:
920
See the `One-to-one relationship model example`_ for a full example.
922
.. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
927
Give your model metadata by using an inner ``class Meta``, like so::
929
class Foo(models.Model):
930
bar = models.CharField(maxlength=30)
935
Model metadata is "anything that's not a field", such as ordering options, etc.
937
Here's a list of all possible ``Meta`` options. No options are required. Adding
938
``class Meta`` to a model is completely optional.
943
The name of the database table to use for the model::
945
db_table = 'music_album'
947
If this isn't given, Django will use ``app_label + '_' + model_class_name``.
948
See "Table names" below for more.
950
If your database table name is an SQL reserved word, or contains characters
951
that aren't allowed in Python variable names -- notably, the hyphen --
952
that's OK. Django quotes column and table names behind the scenes.
957
The name of a ``DateField`` or ``DateTimeField`` in the model. This specifies
958
the default field to use in your model ``Manager``'s ``latest()`` method.
962
get_latest_by = "order_date"
964
See the `docs for latest()`_ for more.
966
.. _docs for latest(): http://www.djangoproject.com/documentation/db_api/#latest-field-name-none
968
``order_with_respect_to``
969
-------------------------
971
Marks this object as "orderable" with respect to the given field. This is
972
almost always used with related objects to allow them to be ordered with
973
respect to a parent object. For example, if an ``Answer`` relates to a
974
``Question`` object, and a question has more than one answer, and the order
975
of answers matters, you'd do this::
977
class Answer(models.Model):
978
question = models.ForeignKey(Question)
982
order_with_respect_to = 'question'
987
The default ordering for the object, for use when obtaining lists of objects::
989
ordering = ['-order_date']
991
This is a tuple or list of strings. Each string is a field name with an
992
optional "-" prefix, which indicates descending order. Fields without a
993
leading "-" will be ordered ascending. Use the string "?" to order randomly.
995
For example, to order by a ``pub_date`` field ascending, use this::
997
ordering = ['pub_date']
999
To order by ``pub_date`` descending, use this::
1001
ordering = ['-pub_date']
1003
To order by ``pub_date`` descending, then by ``author`` ascending, use this::
1005
ordering = ['-pub_date', 'author']
1007
See `Specifying ordering`_ for more examples.
1009
Note that, regardless of how many fields are in ``ordering``, the admin
1010
site uses only the first field.
1012
.. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
1017
Extra permissions to enter into the permissions table when creating this
1018
object. Add, delete and change permissions are automatically created for
1019
each object that has ``admin`` set. This example specifies an extra
1020
permission, ``can_deliver_pizzas``::
1022
permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
1024
This is a list or tuple of 2-tuples in the format
1025
``(permission_code, human_readable_permission_name)``.
1030
Sets of field names that, taken together, must be unique::
1032
unique_together = (("driver", "restaurant"),)
1034
This is a list of lists of fields that must be unique when considered
1035
together. It's used in the Django admin and is enforced at the database
1036
level (i.e., the appropriate ``UNIQUE`` statements are included in the
1037
``CREATE TABLE`` statement).
1042
A human-readable name for the object, singular::
1044
verbose_name = "pizza"
1046
If this isn't given, Django will use a munged version of the class name:
1047
``CamelCase`` becomes ``camel case``.
1049
``verbose_name_plural``
1050
-----------------------
1052
The plural name for the object::
1054
verbose_name_plural = "stories"
1056
If this isn't given, Django will use ``verbose_name + "s"``.
1061
To save you time, Django automatically derives the name of the database table
1062
from the name of your model class and the app that contains it. A model's
1063
database table name is constructed by joining the model's "app label" -- the
1064
name you used in ``manage.py startapp`` -- to the model's class name, with an
1065
underscore between them.
1067
For example, if you have an app ``bookstore`` (as created by
1068
``manage.py startapp bookstore``), a model defined as ``class Book`` will have
1069
a database table named ``bookstore_book``.
1071
To override the database table name, use the ``db_table`` parameter in
1074
Automatic primary key fields
1075
============================
1077
By default, Django gives each model the following field::
1079
id = models.AutoField(primary_key=True)
1081
This is an auto-incrementing primary key.
1083
If you'd like to specify a custom primary key, just specify ``primary_key=True``
1084
on one of your fields. If Django sees you've explicitly set ``primary_key``, it
1085
won't add the automatic ``id`` column.
1087
Each model requires exactly one field to have ``primary_key=True``.
1092
If you want your model to be visible to Django's admin site, give your model an
1093
inner ``"class Admin"``, like so::
1095
class Person(models.Model):
1096
first_name = models.CharField(maxlength=30)
1097
last_name = models.CharField(maxlength=30)
1100
# Admin options go here
1103
The ``Admin`` class tells Django how to display the model in the admin site.
1105
Here's a list of all possible ``Admin`` options. None of these options are
1106
required. To use an admin interface without specifying any options, use
1112
Adding ``class Admin`` to a model is completely optional.
1117
Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
1118
your model, and the change list page will include a date-based drilldown
1119
navigation by that field.
1123
date_hierarchy = 'pub_date'
1128
Set ``fields`` to control the layout of admin "add" and "change" pages.
1130
``fields`` is a list of two-tuples, in which each two-tuple represents a
1131
``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the
1134
The two-tuples are in the format ``(name, field_options)``, where ``name`` is a
1135
string representing the title of the fieldset and ``field_options`` is a
1136
dictionary of information about the fieldset, including a list of fields to be
1139
A full example, taken from the ``django.contrib.flatpages.FlatPage`` model::
1144
'fields': ('url', 'title', 'content', 'sites')
1146
('Advanced options', {
1147
'classes': 'collapse',
1148
'fields' : ('enable_comments', 'registration_required', 'template_name')
1152
This results in an admin page that looks like:
1154
.. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png
1156
If ``fields`` isn't given, Django will default to displaying each field that
1157
isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
1158
the same order as the fields are defined in the model.
1160
The ``field_options`` dictionary can have the following keys:
1165
A tuple of field names to display in this fieldset. This key is required.
1170
'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
1173
To display multiple fields on the same line, wrap those fields in their own
1174
tuple. In this example, the ``first_name`` and ``last_name`` fields will
1175
display on the same line::
1178
'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
1184
A string containing extra CSS classes to apply to the fieldset.
1192
Apply multiple classes by separating them with spaces. Example::
1195
'classes': 'wide extrapretty',
1198
Two useful classes defined by the default admin-site stylesheet are
1199
``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will be
1200
initially collapsed in the admin and replaced with a small "click to expand"
1201
link. Fieldsets with the ``wide`` style will be given extra horizontal space.
1206
A string of optional extra text to be displayed at the top of each fieldset,
1207
under the heading of the fieldset. It's used verbatim, so you can use any HTML
1208
and you must escape any special HTML characters (such as ampersands) yourself.
1213
A list of strings representing URLs of JavaScript files to link into the admin
1214
screen via ``<script src="">`` tags. This can be used to tweak a given type of
1215
admin page in JavaScript or to provide "quick links" to fill in default values
1218
If you use relative URLs -- URLs that don't start with ``http://`` or ``/`` --
1219
then the admin site will automatically prefix these links with
1220
``settings.ADMIN_MEDIA_PREFIX``.
1225
Set ``list_display`` to control which fields are displayed on the change list
1230
list_display = ('first_name', 'last_name')
1232
If you don't set ``list_display``, the admin site will display a single column
1233
that displays the ``__str__()`` representation of each object.
1235
A few special cases to note about ``list_display``:
1237
* If the field is a ``ForeignKey``, Django will display the ``__str__()``
1238
of the related object.
1240
* ``ManyToManyField`` fields aren't supported, because that would entail
1241
executing a separate SQL statement for each row in the table. If you
1242
want to do this nonetheless, give your model a custom method, and add
1243
that method's name to ``list_display``. (See below for more on custom
1244
methods in ``list_display``.)
1246
* If the field is a ``BooleanField`` or ``NullBooleanField``, Django will
1247
display a pretty "on" or "off" icon instead of ``True`` or ``False``.
1249
* If the string given is a method of the model, Django will call it and
1250
display the output. This method should have a ``short_description``
1251
function attribute, for use as the header for the field.
1253
Here's a full example model::
1255
class Person(models.Model):
1256
name = models.CharField(maxlength=50)
1257
birthday = models.DateField()
1260
list_display = ('name', 'decade_born_in')
1262
def decade_born_in(self):
1263
return self.birthday.strftime('%Y')[:3] + "0's"
1264
decade_born_in.short_description = 'Birth decade'
1266
* If the string given is a method of the model, Django will HTML-escape the
1267
output by default. If you'd rather not escape the output of the method,
1268
give the method an ``allow_tags`` attribute whose value is ``True``.
1270
Here's a full example model::
1272
class Person(models.Model):
1273
first_name = models.CharField(maxlength=50)
1274
last_name = models.CharField(maxlength=50)
1275
color_code = models.CharField(maxlength=6)
1278
list_display = ('first_name', 'last_name', 'colored_name')
1280
def colored_name(self):
1281
return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
1282
colored_name.allow_tags = True
1284
* If the string given is a method of the model that returns True or False
1285
Django will display a pretty "on" or "off" icon if you give the method a
1286
``boolean`` attribute whose value is ``True``.
1288
Here's a full example model::
1290
class Person(models.Model):
1291
first_name = models.CharField(maxlength=50)
1292
birthday = models.DateField()
1295
list_display = ('name', 'born_in_fifties')
1297
def born_in_fifties(self):
1298
return self.birthday.strftime('%Y')[:3] == 5
1299
born_in_fifties.boolean = True
1302
* The ``__str__()`` method is just as valid in ``list_display`` as any
1303
other model method, so it's perfectly OK to do this::
1305
list_display = ('__str__', 'some_other_field')
1307
* Usually, elements of ``list_display`` that aren't actual database fields
1308
can't be used in sorting (because Django does all the sorting at the
1311
However, if an element of ``list_display`` represents a certain database
1312
field, you can indicate this fact by setting the ``admin_order_field``
1313
attribute of the item.
1317
class Person(models.Model):
1318
first_name = models.CharField(maxlength=50)
1319
color_code = models.CharField(maxlength=6)
1322
list_display = ('first_name', 'colored_first_name')
1324
def colored_first_name(self):
1325
return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
1326
colored_first_name.allow_tags = True
1327
colored_first_name.admin_order_field = 'first_name'
1329
The above will tell Django to order by the ``first_name`` field when
1330
trying to sort by ``colored_first_name`` in the admin.
1332
``list_display_links``
1333
----------------------
1335
Set ``list_display_links`` to control which fields in ``list_display`` should
1336
be linked to the "change" page for an object.
1338
By default, the change list page will link the first column -- the first field
1339
specified in ``list_display`` -- to the change page for each item. But
1340
``list_display_links`` lets you change which columns are linked. Set
1341
``list_display_links`` to a list or tuple of field names (in the same format as
1342
``list_display``) to link.
1344
``list_display_links`` can specify one or many field names. As long as the
1345
field names appear in ``list_display``, Django doesn't care how many (or how
1346
few) fields are linked. The only requirement is: If you want to use
1347
``list_display_links``, you must define ``list_display``.
1349
In this example, the ``first_name`` and ``last_name`` fields will be linked on
1350
the change list page::
1353
list_display = ('first_name', 'last_name', 'birthday')
1354
list_display_links = ('first_name', 'last_name')
1356
Finally, note that in order to use ``list_display_links``, you must define
1357
``list_display``, too.
1362
Set ``list_filter`` to activate filters in the right sidebar of the change list
1363
page of the admin. This should be a list of field names, and each specified
1364
field should be either a ``BooleanField``, ``DateField``, ``DateTimeField``
1367
This example, taken from the ``django.contrib.auth.models.User`` model, shows
1368
how both ``list_display`` and ``list_filter`` work::
1371
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
1372
list_filter = ('is_staff', 'is_superuser')
1374
The above code results in an admin change list page that looks like this:
1376
.. image:: http://media.djangoproject.com/img/doc/users_changelist.png
1378
(This example also has ``search_fields`` defined. See below.)
1383
Set ``list_per_page`` to control how many items appear on each paginated admin
1384
change list page. By default, this is set to ``100``.
1386
``list_select_related``
1387
-----------------------
1389
Set ``list_select_related`` to tell Django to use ``select_related()`` in
1390
retrieving the list of objects on the admin change list page. This can save you
1391
a bunch of database queries.
1393
The value should be either ``True`` or ``False``. Default is ``False``.
1395
Note that Django will use ``select_related()``, regardless of this setting,
1396
if one of the ``list_display`` fields is a ``ForeignKey``.
1398
For more on ``select_related()``, see `the select_related() docs`_.
1400
.. _the select_related() docs: http://www.djangoproject.com/documentation/db_api/#select-related
1405
Set ``ordering`` to specify how objects on the admin change list page should be
1406
ordered. This should be a list or tuple in the same format as a model's
1407
``ordering`` parameter.
1409
If this isn't provided, the Django admin will use the model's default ordering.
1414
Set ``save_as`` to enable a "save as" feature on admin change forms.
1416
Normally, objects have three save options: "Save", "Save and continue editing"
1417
and "Save and add another". If ``save_as`` is ``True``, "Save and add another"
1418
will be replaced by a "Save as" button.
1420
"Save as" means the object will be saved as a new object (with a new ID),
1421
rather than the old object.
1423
By default, ``save_as`` is set to ``False``.
1428
Set ``save_on_top`` to add save buttons across the top of your admin change
1431
Normally, the save buttons appear only at the bottom of the forms. If you set
1432
``save_on_top``, the buttons will appear both on the top and the bottom.
1434
By default, ``save_on_top`` is set to ``False``.
1439
Set ``search_fields`` to enable a search box on the admin change list page.
1440
This should be set to a list of field names that will be searched whenever
1441
somebody submits a search query in that text box.
1443
These fields should be some kind of text field, such as ``CharField`` or
1444
``TextField``. You can also perform a related lookup on a ``ForeignKey`` with
1445
the lookup API "follow" notation::
1447
search_fields = ['foreign_key__related_fieldname']
1449
When somebody does a search in the admin search box, Django splits the search
1450
query into words and returns all objects that contain each of the words, case
1451
insensitive, where each word must be in at least one of ``search_fields``. For
1452
example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a
1453
user searches for ``john lennon``, Django will do the equivalent of this SQL
1456
WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
1457
AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
1459
For faster and/or more restrictive searches, prefix the field name
1463
Matches the beginning of the field. For example, if ``search_fields`` is
1464
set to ``['^first_name', '^last_name']`` and a user searches for
1465
``john lennon``, Django will do the equivalent of this SQL ``WHERE``
1468
WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
1469
AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
1471
This query is more efficient than the normal ``'%john%'`` query, because
1472
the database only needs to check the beginning of a column's data, rather
1473
than seeking through the entire column's data. Plus, if the column has an
1474
index on it, some databases may be able to use the index for this query,
1475
even though it's a ``LIKE`` query.
1478
Matches exactly, case-insensitive. For example, if
1479
``search_fields`` is set to ``['=first_name', '=last_name']`` and
1480
a user searches for ``john lennon``, Django will do the equivalent
1481
of this SQL ``WHERE`` clause::
1483
WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
1484
AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
1486
Note that the query input is split by spaces, so, following this example,
1487
it's not currently not possible to search for all records in which
1488
``first_name`` is exactly ``'john winston'`` (containing a space).
1491
Performs a full-text match. This is like the default search method but uses
1492
an index. Currently this is only available for MySQL.
1497
A ``Manager`` is the interface through which database query operations are
1498
provided to Django models. At least one ``Manager`` exists for every model in
1499
a Django application.
1501
The way ``Manager`` classes work is documented in the `Retrieving objects`_
1502
section of the database API docs, but this section specifically touches on
1503
model options that customize ``Manager`` behavior.
1505
.. _Retrieving objects: http://www.djangoproject.com/documentation/db_api/#retrieving-objects
1510
By default, Django adds a ``Manager`` with the name ``objects`` to every Django
1511
model class. However, if you want to use ``objects`` as a field name, or if you
1512
want to use a name other than ``objects`` for the ``Manager``, you can rename
1513
it on a per-model basis. To rename the ``Manager`` for a given class, define a
1514
class attribute of type ``models.Manager()`` on that model. For example::
1516
from django.db import models
1518
class Person(models.Model):
1520
people = models.Manager()
1522
Using this example model, ``Person.objects`` will generate an
1523
``AttributeError`` exception, but ``Person.people.all()`` will provide a list
1524
of all ``Person`` objects.
1529
You can use a custom ``Manager`` in a particular model by extending the base
1530
``Manager`` class and instantiating your custom ``Manager`` in your model.
1532
There are two reasons you might want to customize a ``Manager``: to add extra
1533
``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
1536
Adding extra Manager methods
1537
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1539
Adding extra ``Manager`` methods is the preferred way to add "table-level"
1540
functionality to your models. (For "row-level" functionality -- i.e., functions
1541
that act on a single instance of a model object -- use _`Model methods`, not
1542
custom ``Manager`` methods.)
1544
A custom ``Manager`` method can return anything you want. It doesn't have to
1545
return a ``QuerySet``.
1547
For example, this custom ``Manager`` offers a method ``with_counts()``, which
1548
returns a list of all ``OpinionPoll`` objects, each with an extra
1549
``num_responses`` attribute that is the result of an aggregate query::
1551
class PollManager(models.Manager):
1552
def with_counts(self):
1553
from django.db import connection
1554
cursor = connection.cursor()
1556
SELECT p.id, p.question, p.poll_date, COUNT(*)
1557
FROM polls_opinionpoll p, polls_response r
1558
WHERE p.id = r.poll_id
1562
for row in cursor.fetchall():
1563
p = self.model(id=row[0], question=row[1], poll_date=row[2])
1564
p.num_responses = row[3]
1565
result_list.append(p)
1568
class OpinionPoll(models.Model):
1569
question = models.CharField(maxlength=200)
1570
poll_date = models.DateField()
1571
objects = PollManager()
1573
class Response(models.Model):
1574
poll = models.ForeignKey(Poll)
1575
person_name = models.CharField(maxlength=50)
1576
response = models.TextField()
1578
With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return
1579
that list of ``OpinionPoll`` objects with ``num_responses`` attributes.
1581
Another thing to note about this example is that ``Manager`` methods can
1582
access ``self.model`` to get the model class to which they're attached.
1584
Modifying initial Manager QuerySets
1585
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1587
A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
1588
example, using this model::
1590
class Book(models.Model):
1591
title = models.CharField(maxlength=100)
1592
author = models.CharField(maxlength=50)
1594
...the statement ``Book.objects.all()`` will return all books in the database.
1596
You can override a ``Manager``\'s base ``QuerySet`` by overriding the
1597
``Manager.get_query_set()`` method. ``get_query_set()`` should return a
1598
``QuerySet`` with the properties you require.
1600
For example, the following model has *two* ``Manager``\s -- one that returns
1601
all objects, and one that returns only the books by Roald Dahl::
1603
# First, define the Manager subclass.
1604
class DahlBookManager(models.Manager):
1605
def get_query_set(self):
1606
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
1608
# Then hook it into the Book model explicitly.
1609
class Book(models.Model):
1610
title = models.CharField(maxlength=100)
1611
author = models.CharField(maxlength=50)
1613
objects = models.Manager() # The default manager.
1614
dahl_objects = DahlBookManager() # The Dahl-specific manager.
1616
With this sample model, ``Book.objects.all()`` will return all books in the
1617
database, but ``Book.dahl_objects.all()`` will only return the ones written by
1620
Of course, because ``get_query_set()`` returns a ``QuerySet`` object, you can
1621
use ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it.
1622
So these statements are all legal::
1624
Book.dahl_objects.all()
1625
Book.dahl_objects.filter(title='Matilda')
1626
Book.dahl_objects.count()
1628
This example also pointed out another interesting technique: using multiple
1629
managers on the same model. You can attach as many ``Manager()`` instances to
1630
a model as you'd like. This is an easy way to define common "filters" for your
1635
class MaleManager(models.Manager):
1636
def get_query_set(self):
1637
return super(MaleManager, self).get_query_set().filter(sex='M')
1639
class FemaleManager(models.Manager):
1640
def get_query_set(self):
1641
return super(FemaleManager, self).get_query_set().filter(sex='F')
1643
class Person(models.Model):
1644
first_name = models.CharField(maxlength=50)
1645
last_name = models.CharField(maxlength=50)
1646
sex = models.CharField(maxlength=1, choices=(('M', 'Male'), ('F', 'Female')))
1647
people = models.Manager()
1649
women = FemaleManager()
1651
This example allows you to request ``Person.men.all()``, ``Person.women.all()``,
1652
and ``Person.people.all()``, yielding predictable results.
1654
If you use custom ``Manager`` objects, take note that the first ``Manager``
1655
Django encounters (in order by which they're defined in the model) has a
1656
special status. Django interprets the first ``Manager`` defined in a class as
1657
the "default" ``Manager``. Certain operations -- such as Django's admin site --
1658
use the default ``Manager`` to obtain lists of objects, so it's generally a
1659
good idea for the first ``Manager`` to be relatively unfiltered. In the last
1660
example, the ``people`` ``Manager`` is defined first -- so it's the default
1666
Define custom methods on a model to add custom "row-level" functionality to
1667
your objects. Whereas ``Manager`` methods are intended to do "table-wide"
1668
things, model methods should act on a particular model instance.
1670
This is a valuable technique for keeping business logic in one place -- the
1673
For example, this model has a few custom methods::
1675
class Person(models.Model):
1676
first_name = models.CharField(maxlength=50)
1677
last_name = models.CharField(maxlength=50)
1678
birth_date = models.DateField()
1679
address = models.CharField(maxlength=100)
1680
city = models.CharField(maxlength=50)
1681
state = models.USStateField() # Yes, this is America-centric...
1683
def baby_boomer_status(self):
1684
"Returns the person's baby-boomer status."
1686
if datetime.date(1945, 8, 1) <= self.birth_date <= datetime.date(1964, 12, 31):
1687
return "Baby boomer"
1688
if self.birth_date < datetime.date(1945, 8, 1):
1690
return "Post-boomer"
1692
def is_midwestern(self):
1693
"Returns True if this person is from the Midwest."
1694
return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
1696
def _get_full_name(self):
1697
"Returns the person's full name."
1698
return '%s %s' % (self.first_name, self.last_name)
1699
full_name = property(_get_full_name)
1701
The last method in this example is a *property*. `Read more about properties`_.
1703
.. _Read more about properties: http://www.python.org/download/releases/2.2/descrintro/#property
1705
A few object methods have special meaning:
1710
``__str__()`` is a Python "magic method" that defines what should be returned
1711
if you call ``str()`` on the object. Django uses ``str(obj)`` in a number of
1712
places, most notably as the value displayed to render an object in the Django
1713
admin site and as the value inserted into a template when it displays an
1714
object. Thus, you should always return a nice, human-readable string for the
1715
object's ``__str__``. Although this isn't required, it's strongly encouraged.
1719
class Person(models.Model):
1720
first_name = models.CharField(maxlength=50)
1721
last_name = models.CharField(maxlength=50)
1724
return '%s %s' % (self.first_name, self.last_name)
1726
``get_absolute_url``
1727
--------------------
1729
Define a ``get_absolute_url()`` method to tell Django how to calculate the
1730
URL for an object. For example::
1732
def get_absolute_url(self):
1733
return "/people/%i/" % self.id
1735
Django uses this in its admin interface. If an object defines
1736
``get_absolute_url()``, the object-editing page will have a "View on site"
1737
link that will jump you directly to the object's public view, according to
1738
``get_absolute_url()``.
1740
Also, a couple of other bits of Django, such as the syndication-feed framework,
1741
use ``get_absolute_url()`` as a convenience to reward people who've defined the
1744
It's good practice to use ``get_absolute_url()`` in templates, instead of
1745
hard-coding your objects' URLs. For example, this template code is bad::
1747
<a href="/people/{{ object.id }}/">{{ object.name }}</a>
1749
But this template code is good::
1751
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
1753
The ``permalink`` decorator
1754
~~~~~~~~~~~~~~~~~~~~~~~~~~~
1756
The problem with the way we wrote ``get_absolute_url()`` above is that it
1757
slightly violates the DRY principle: the URL for this object is defined both
1758
in the URLConf file and in the model.
1760
You can further decouple your models from the URLconf using the ``permalink``
1761
decorator. This decorator is passed the view function and any parameters you
1762
would use for accessing this instance directly. Django then works out the
1763
correct full URL path using the URLconf. For example::
1765
from django.db.models import permalink
1767
def get_absolute_url(self):
1768
return ('people.views.details', str(self.id))
1769
get_absolute_url = permalink(get_absolute_url)
1771
In this way, you're tying the model's absolute URL to the view that is used
1772
to display it, without repeating the URL information anywhere. You can still
1773
use the ``get_absolute_url`` method in templates, as before.
1775
Executing custom SQL
1776
--------------------
1778
Feel free to write custom SQL statements in custom model methods and
1779
module-level methods. The object ``django.db.connection`` represents the
1780
current database connection. To use it, call ``connection.cursor()`` to get a
1781
cursor object. Then, call ``cursor.execute(sql, [params])`` to execute the SQL
1782
and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the resulting
1785
def my_custom_sql(self):
1786
from django.db import connection
1787
cursor = connection.cursor()
1788
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
1789
row = cursor.fetchone()
1792
``connection`` and ``cursor`` simply use the standard `Python DB-API`_. If
1793
you're not familiar with the Python DB-API, note that the SQL statement in
1794
``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters
1795
directly within the SQL. If you use this technique, the underlying database
1796
library will automatically add quotes and escaping to your parameter(s) as
1797
necessary. (Also note that Django expects the ``"%s"`` placeholder, *not* the
1798
``"?"`` placeholder, which is used by the SQLite Python bindings. This is for
1799
the sake of consistency and sanity.)
1801
A final note: If all you want to do is a custom ``WHERE`` clause, you can just
1802
just the ``where``, ``tables`` and ``params`` arguments to the standard lookup
1803
API. See `Other lookup options`_.
1805
.. _Python DB-API: http://www.python.org/peps/pep-0249.html
1806
.. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables
1808
Overriding default model methods
1809
--------------------------------
1811
As explained in the `database API docs`_, each model gets a few methods
1812
automatically -- most notably, ``save()`` and ``delete()``. You can override
1813
these methods to alter behavior.
1815
A classic use-case for overriding the built-in methods is if you want something
1816
to happen whenever you save an object. For example::
1818
class Blog(models.Model):
1819
name = models.CharField(maxlength=100)
1820
tagline = models.TextField()
1824
super(Blog, self).save() # Call the "real" save() method.
1827
You can also prevent saving::
1829
class Blog(models.Model):
1830
name = models.CharField(maxlength=100)
1831
tagline = models.TextField()
1834
if self.name == "Yoko Ono's blog":
1835
return # Yoko shall never have her own blog!
1837
super(Blog, self).save() # Call the "real" save() method.
1839
.. _database API docs: http://www.djangoproject.com/documentation/db_api/
1844
It's perfectly OK to relate a model to one from another app. To do this, just
1845
import the related model at the top of the model that holds your model. Then,
1846
just refer to the other model class wherever needed. For example::
1848
from mysite.geography.models import ZipCode
1850
class Restaurant(models.Model):
1852
zip_code = models.ForeignKey(ZipCode)
1857
Once you have created your models, the final step is to tell Django you're
1858
going to *use* those models.
1860
Do this by editing your settings file and changing the ``INSTALLED_APPS``
1861
setting to add the name of the module that contains your ``models.py``.
1863
For example, if the models for your application live in the module
1864
``mysite.myapp.models`` (the package structure that is created for an
1865
application by the ``manage.py startapp`` script), ``INSTALLED_APPS`` should
1874
Providing initial SQL data
1875
==========================
1877
Django provides a hook for passing the database arbitrary SQL that's executed
1878
just after the CREATE TABLE statements. Use this hook, for example, if you want
1879
to populate default records, or create SQL functions, automatically.
1881
The hook is simple: Django just looks for a file called
1882
``<appname>/sql/<modelname>.sql``, where ``<appname>`` is your app directory and
1883
``<modelname>`` is the model's name in lowercase.
1885
In the ``Person`` example model at the top of this document, assuming it lives
1886
in an app called ``myapp``, you could add arbitrary SQL to the file
1887
``myapp/sql/person.sql``. Here's an example of what the file might contain::
1889
INSERT INTO myapp_person (first_name, last_name) VALUES ('John', 'Lennon');
1890
INSERT INTO myapp_person (first_name, last_name) VALUES ('Paul', 'McCartney');
1892
Each SQL file, if given, is expected to contain valid SQL. The SQL files are
1893
piped directly into the database after all of the models' table-creation
1894
statements have been executed.
1896
The SQL files are read by the ``sqlinitialdata``, ``sqlreset``, ``sqlall`` and
1897
``reset`` commands in ``manage.py``. Refer to the `manage.py documentation`_
1898
for more information.
1900
Note that if you have multiple SQL data files, there's no guarantee of the
1901
order in which they're executed. The only thing you can assume is that, by the
1902
time your custom data files are executed, all the database tables already will
1905
.. _`manage.py documentation`: http://www.djangoproject.com/documentation/django_admin/#sqlinitialdata-appname-appname
1907
Database-backend-specific SQL data
1908
----------------------------------
1910
There's also a hook for backend-specific SQL data. For example, you can have
1911
separate initial-data files for PostgreSQL and MySQL. For each app, Django
1912
looks for a file called ``<appname>/sql/<modelname>.<backend>.sql``, where
1913
``<appname>`` is your app directory, ``<modelname>`` is the model's name in
1914
lowercase and ``<backend>`` is the value of ``DATABASE_ENGINE`` in your
1915
settings file (e.g., ``postgresql``, ``mysql``).
1917
Backend-specific SQL data is executed before non-backend-specific SQL data. For
1918
example, if your app contains the files ``sql/person.sql`` and
1919
``sql/person.postgresql.sql`` and you're installing the app on PostgreSQL,
1920
Django will execute the contents of ``sql/person.postgresql.sql`` first, then