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.core.meta.Model``.
12 * Each attribute of the model represents a database field.
13 * Model metadata (non-field information) goes in an inner class named ``META``.
15 A companion to this document is the `official repository of model examples`_.
17 .. _`official repository of model examples`: http://www.djangoproject.com/documentation/models/
22 The most important part of a model is the list of database fields it defines.
23 Fields are defined by class attributes. Each class attribute in a model, aside
24 from the optional inner ``class META``, should be an instance of a
25 ``meta.Field`` subclass.
27 In this example, there are two fields, ``first_name`` and ``last_name`` ::
29 class Person(meta.Model):
30 first_name = meta.CharField(maxlength=30)
31 last_name = meta.CharField(maxlength=30)
33 Django will use ``first_name`` and ``last_name`` as the database column names.
35 Each field type, except for ``ForeignKey``, ``ManyToManyField`` and
36 ``OneToOneField``, takes an optional first positional argument -- a
37 human-readable name. If the human-readable name isn't given, Django will
38 automatically create the human-readable name by using the machine-readable
39 name, converting underscores to spaces.
41 In this example, the human-readable name is ``"Person's first name"``::
43 first_name = meta.CharField("Person's first name", maxlength=30)
45 In this example, the human-readable name is ``"first name"``::
47 first_name = meta.CharField(maxlength=30)
49 ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
50 argument to be a model class, so use the ``verbose_name`` keyword argument to
51 specify the human-readable name::
53 poll = meta.ForeignKey(Poll, verbose_name="the related poll")
54 sites = meta.ManyToManyField(Site, verbose_name="list of sites")
55 place = meta.OneToOneField(Place, verbose_name="related place")
57 Convention is not to capitalize the first letter of the ``verbose_name``.
58 Django will automatically capitalize the first letter where it needs to.
63 The following arguments are available to all field types. All are optional.
66 If ``True``, Django will store empty values as ``NULL`` in the database.
69 Note that empty string values will always get stored as empty strings, not
70 as ``NULL`` -- so use ``null=True`` for non-string fields such as integers,
73 Avoid using ``null`` on string-based fields such as ``CharField`` and
74 ``TextField`` unless you have an excellent reason. If a string-based field
75 has ``null=True``, that means it has two possible values for "no data":
76 ``NULL``, and the empty string. In most cases, it's redundant to have two
77 possible values for "no data;" Django convention is to use the empty
81 If ``True``, the field is allowed to be blank.
83 Note that this is different than ``null``. ``null`` is purely
84 database-related, whereas ``blank`` is validation-related. If a field has
85 ``blank=True``, validation on Django's admin site will allow entry of an
86 empty value. If a field has ``blank=False``, the field will be required.
89 A list of 2-tuples to use as choices for this field.
91 If this is given, Django's admin will use a select box instead of the
92 standard text field and will limit choices to the choices given.
94 A choices list looks like this::
96 YEAR_IN_SCHOOL_CHOICES = (
104 The first element in each tuple is the actual value to be stored. The
105 second element is the human-readable name for the option.
108 For objects that are edited inline to a related object.
110 In the Django admin, if all "core" fields in an inline-edited object are
111 cleared, the object will be deleted.
113 It is an error to have an inline-editable relation without at least one
117 The name of the database column to use for this field. If this isn't given,
118 Django will use the field's name.
120 If your database column name is an SQL reserved word, or contains
121 characters that aren't allowed in Python variable names -- notably, the
122 hyphen -- that's OK. Django quotes column and table names behind the
126 If ``True``, ``django-admin.py sqlindexes`` will output a ``CREATE INDEX``
127 statement for this field.
130 The default value for the field.
133 If ``False``, the field will not be editable in the admin. Default is ``True``.
136 Extra "help" text to be displayed under the field on the object's admin
137 form. It's useful for documentation even if your object doesn't have an
141 If ``True``, this field is the primary key for the model.
143 If you don't specify ``primary_key=True`` for any fields in your model,
144 Django will automatically add this field::
146 id = meta.AutoField('ID', primary_key=True)
148 Thus, you don't need to set ``primary_key=True`` on any of your fields
149 unless you want to override the default primary-key behavior.
151 ``primary_key=True`` implies ``blank=False``, ``null=False`` and
152 ``unique=True``. Only one primary key is allowed on an object.
155 By default, Django's admin uses a select-box interface (<select>) for
156 fields that are ``ForeignKey`` or have ``choices`` set. If ``radio_admin``
157 is set to ``True``, Django will use a radio-button interface instead.
159 Don't use this for a field unless it's a ``ForeignKey`` or has ``choices``
163 If ``True``, this field must be unique throughout the table.
165 This is enforced at the database level and at the Django admin-form level.
168 Set this to the name of a ``DateField`` or ``DateTimeField`` to require
169 that this field be unique for the value of the date field.
171 For example, if you have a field ``title`` that has
172 ``unique_for_date="pub_date"``, then Django wouldn't allow the entry of
173 two records with the same ``title`` and ``pub_date``.
175 This is enforced at the Django admin-form level but not at the database level.
178 Like ``unique_for_date``, but requires the field to be unique with respect
182 Like ``unique_for_date`` and ``unique_for_month``.
185 A list of extra validators to apply to the field. Each should be a callable
186 that takes the parameters ``field_data, all_data`` and raises
187 ``django.core.validators.ValidationError`` for errors. (See the
190 Django comes with quite a few validators. They're in ``django.core.validators``.
192 .. _validator docs: http://www.djangoproject.com/documentation/forms/#validators
197 Each field in your model should be an instance of the appropriate ``Field``
198 class. Django uses the field class types to determine a few things:
200 * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
201 * The widget to use in Django's admin (e.g. ``<input type="text">``, ``<select>``).
202 * The minimal validation requirements, used in Django's admin and in manipulators.
204 Here are all available field types:
207 An ``IntegerField`` that automatically increments according to available
208 IDs. You usually won't need to use this directly; a primary key field will
209 automatically be added to your model if you don't specify otherwise. (See
210 ``primary_key`` in ``General field options`` above.)
215 The admin represents this as a checkbox.
218 A string field, for small- to large-sized strings.
220 For large amounts of text, use ``TextField``.
222 The admin represents this as an ``<input type="text">`` (a single-line input).
224 ``CharField`` has an extra required argument, ``maxlength``, the maximum
225 length (in characters) of the field. The maxlength is enforced at the
226 database level and in Django's validation.
228 ``CommaSeparatedIntegerField``
229 A field of integers separated by commas. As in ``CharField``, the
230 ``maxlength`` argument is required.
233 A date field. Has a few extra optional arguments:
235 ====================== ===================================================
237 ====================== ===================================================
238 ``auto_now`` Automatically set the field to now every time the
239 object is saved. Useful for "last-modified"
242 ``auto_now_add`` Automatically set the field to now when the object
243 is first created. Useful for creation of
245 ====================== ===================================================
247 The admin represents this as an ``<input type="text">`` with a JavaScript
248 calendar and a shortcut for "Today."
251 A date and time field. Takes the same extra options as ``DateField``.
253 The admin represents this as two ``<input type="text">`` fields, with
254 JavaScript shortcuts.
257 A ``CharField`` that checks that the value is a valid e-mail address.
258 This doesn't accept ``maxlength``.
263 Has an extra required argument, ``upload_to``, a local filesystem path to
264 which files should be upload. This path may contain `strftime formatting`_,
265 which will be replaced by the date/time of the file upload (so that
266 uploaded files don't fill up the given directory).
268 The admin represents this as an ``<input type="file">`` (a file-upload widget).
270 Using a ``FileField` or an ``ImageField`` (see below) in a model takes a few
273 1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
274 full path to a directory where you'd like Django to store uploaded
275 files. (For performance, these files are not stored in the database.)
276 Define ``MEDIA_URL`` as the base public URL of that directory. Make
277 sure that this directory is writable by the Web server's user
280 2. Add the ``FileField`` or ``ImageField`` to your model, making sure
281 to define the ``upload_to`` option to tell Django to which
282 subdirectory of ``MEDIA_ROOT`` it should upload files.
284 3. All that will be stored in your database is a path to the file
285 (relative to ``MEDIA_ROOT``). You'll must likely want to use the
286 convenience ``get_<fieldname>_url`` function provided by Django. For
287 example, if your ``ImageField`` is called ``mug_shot``, you can get
288 the absolute URL to your image in a template with ``{{
289 object.get_mug_shot_url }}``.
291 .. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941
294 A field whose choices are limited to the filenames in a certain directory
295 on the filesystem. Has three special arguments, of which the first is
298 ====================== ===================================================
300 ====================== ===================================================
301 ``path`` Required. The absolute filesystem path to a
302 directory from which this ``FilePathField`` should
303 get its choices. Example: ``"/home/images"``.
305 ``match`` Optional. A regular expression, as a string, that
306 ``FilePathField`` will use to filter filenames.
307 Note that the regex will be applied to the
308 base filename, not the full path. Example:
309 ``"foo.*\.txt^"``, which will match a file called
310 ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.
312 ``recursive`` Optional. Either ``True`` or ``False``. Default is
313 ``False``. Specifies whether all subdirectories of
314 ``path`` should be included.
315 ====================== ===================================================
317 Of course, these arguments can be used together.
319 The one potential gotcha is that ``match`` applies to the base filename,
320 not the full path. So, this example::
322 FilePathField(path="/home/images", match="foo.*", recursive=True)
324 ...will match ``/home/images/foo.gif`` but not ``/home/images/foo/bar.gif``
325 because the ``match`` applies to the base filename (``foo.gif`` and
329 A floating-point number. Has two **required** arguments:
331 ====================== ===================================================
333 ====================== ===================================================
334 ``max_digits`` The maximum number of digits allowed in the number.
336 ``decimal_places`` The number of decimal places to store with the
338 ====================== ===================================================
340 For example, to store numbers up to 999 with a resolution of 2 decimal places,
343 meta.FloatField(..., max_digits=5, decimal_places=2)
345 And to store numbers up to one million with a resolution of 10 decimal places::
347 meta.FloatField(..., max_digits=19, decimal_places=10)
349 The admin represents this as an ``<input type="text">`` (a single-line input).
352 Like ``FileField``, but validates that the uploaded object is a valid
353 image. Has two extra optional arguments, ``height_field`` and
354 ``width_field``, which, if set, will be auto-populated with the height and
355 width of the image each time a model instance is saved.
357 Requires the `Python Imaging Library`_.
359 .. _Python Imaging Library: http://www.pythonware.com/products/pil/
364 The admin represents this as an ``<input type="text">`` (a single-line input).
367 An IP address, in string format (i.e. "24.124.1.30").
369 The admin represents this as an ``<input type="text">`` (a single-line input).
372 Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use this
373 instead of a ``BooleanField`` with ``null=True``.
375 The admin represents this as a ``<select>`` box with "Unknown", "Yes" and "No" choices.
378 A ``CharField`` that checks that the value is a valid U.S.A.-style phone
379 number (in the format ``XXX-XXX-XXXX``).
381 ``PositiveIntegerField``
382 Like an ``IntegerField``, but must be positive.
384 ``PositiveSmallIntegerField``
385 Like a ``PositiveIntegerField``, but only allows values under a certain
386 (database-dependent) point.
389 "Slug" is a newspaper term. A slug is a short label for something,
390 containing only letters, numbers, underscores or hyphens. They're generally
393 Implies ``maxlength=50`` and ``db_index=True``.
395 Accepts an extra option, ``prepopulate_from``, which is a list of fields
396 from which to auto-populate the slug, via JavaScript, in the object's admin
399 meta.SlugField(prepopulate_from=("pre_name", "name"))
401 ``prepopulate_from`` doesn't accept DateTimeFields.
403 The admin represents ``SlugField`` as an ``<input type="text">`` (a
406 ``SmallIntegerField``
407 Like an ``IntegerField``, but only allows values under a certain
408 (database-dependent) point.
413 The admin represents this as a ``<textarea>`` (a multi-line input).
416 A time. Accepts the same auto-population options as ``DateField`` and
419 The admin represents this as an ``<input type="text">`` with some
420 JavaScript shortcuts.
423 A field for a URL. If the ``verify_exists`` option is ``True`` (default),
424 the URL given will be checked for existence (i.e., the URL actually loads
425 and doesn't give a 404 response).
427 The admin represents this as an ``<input type="text">`` (a single-line input).
430 A two-letter U.S. state abbreviation.
432 The admin represents this as an ``<input type="text">`` (a single-line input).
435 A ``TextField`` that checks that the value is valid XML that matches a
436 given schema. Takes one required argument, ``schema_path``, which is the
437 filesystem path to a RelaxNG_ schema against which to validate the field.
439 .. _RelaxNG: http://www.relaxng.org/
444 Clearly, the power of relational databases lies in relating tables to each
445 other. Django offers ways to define the most common types of database
446 relationships: Many-to-one, many-to-many and one-to-one.
448 Many-to-one relationships
449 ~~~~~~~~~~~~~~~~~~~~~~~~~
451 To define a many-to-one relationship, use ``ForeignKey``. You use it just like
452 any other ``Field`` type: by including it as a class attribute of your model.
454 ``ForeignKey`` requires a positional argument: The class to which the model is
457 For example, if a ``Place`` model is in a ``City`` -- that is, a ``City``
458 contains multiple places but each ``Place`` is only in one ``City`` -- here's
459 how you'd represent that::
461 class City(meta.Model):
464 class Place(meta.Model):
466 city = meta.ForeignKey(City)
468 To create a recursive relationship -- an object that has a many-to-one
469 relationship with itself -- use ``meta.ForeignKey("self")``.
471 The name of a ``ForeignKey`` (``city`` in the example above) generally should
472 be the name of the model, singular. Behind the scenes, Django appends "_id" to
473 the field name to create its database column name. But your code should never
474 have to deal with the database column name, unless you write custom SQL.
476 See the `Many-to-one relationship model example`_ for a full example.
478 .. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
480 ``ForeignKey`` fields take a number of extra arguments for defining how the
481 relationship should work. All are optional:
483 ======================= ============================================================
485 ======================= ============================================================
486 ``edit_inline`` If not ``False``, this related object is edited
487 "inline" on the related object's page. This means
488 that the object will not have its own admin
489 interface. Use either ``meta.TABULAR`` or ``meta.STACKED``,
490 which, respectively, designate whether the inline-editable
491 objects are displayed as a table or as a "stack" of
494 ``limit_choices_to`` A dictionary of lookup arguments and values (see
495 the `Database API reference`_) that limit the
496 available admin choices for this object. Use this
497 with ``meta.LazyDate`` to limit choices of objects
498 by date. For example::
500 limit_choices_to = {'pub_date__lte' : meta.LazyDate()}
502 only allows the choice of related objects with a
503 ``pub_date`` before the current date/time to be
506 Not compatible with ``edit_inline``.
508 ``max_num_in_admin`` For inline-edited objects, this is the maximum
509 number of related objects to display in the admin.
510 Thus, if a pizza could only have up to 10
511 toppings, ``max_num_in_admin=10`` would ensure
512 that a user never enters more than 10 toppings.
514 Note that this doesn't ensure more than 10 related
515 toppings ever get created. It just controls the
518 ``min_num_in_admin`` The minimum number of related objects displayed in
519 the admin. Normally, at the creation stage,
520 ``num_in_admin`` inline objects are shown, and at
521 the edit stage ``num_extra_on_change`` blank
522 objects are shown in addition to all pre-existing
523 related objects. However, no fewer than
524 ``min_num_in_admin`` related objects will ever be
527 ``num_extra_on_change`` The number of extra blank related-object fields to
528 show at the change stage.
530 ``num_in_admin`` The default number of inline objects to display
531 on the object page at the add stage.
533 ``raw_id_admin`` Only display a field for the integer to be entered
534 instead of a drop-down menu. This is useful when
535 related to an object type that will have too many
536 rows to make a select box practical.
538 Not used with ``edit_inline``.
540 ``related_name`` The name to use for the relation from the related
541 object back to this one. For example, when if
542 ``Topping`` has this field::
544 meta.ForeignKey(Pizza)
546 the ``related_name`` will be "topping" (taken from
547 the class name), which will in turn give ``Pizza``
548 the methods ``get_topping_list()`` and
549 ``get_topping_count()``.
551 If you instead were to use::
553 meta.ForeignKey(Pizza, related_name="munchie")
555 then the methods would be called
556 ``get_munchie_list()``, ``get_munchie_count()``,
559 This is only really useful when you have a single
560 object that relates to the same object more than
561 once. For example, if a ``Story`` object has both
562 ``primary_category`` and ``secondary_category``
563 fields, to make sure that the ``Category`` objects
564 have the correct methods, you'd use fields like::
566 meta.ForeignKey(Category, related_name="primary_story")
567 meta.ForeignKey(Category, related_name="secondary_story")
569 ...which would give the ``Category`` objects
570 methods named ``get_primary_story_list()`` and
571 ``get_secondary_story_list()``.
573 ``to_field`` The field on the related object that the relation
574 is to. By default, Django uses the primary key of
576 ======================= ============================================================
578 .. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/
580 Many-to-many relationships
581 ~~~~~~~~~~~~~~~~~~~~~~~~~~
583 To define a many-to-many relationship, use ``ManyToManyField``. You use it just
584 like any other ``Field`` type: by including it as a class attribute of your
587 ``ManyToManyField`` requires a positional argument: The class to which the
590 For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
591 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings --
592 here's how you'd represent that::
594 class Topping(meta.Model):
597 class Pizza(meta.Model):
599 toppings = meta.ManyToManyField(Topping)
601 The name of a ``ManyToManyField`` (``toppings`` in the example above) generally
602 should be the name of the model, plural.
604 Behind the scenes, Django creates an intermediary join table to represent the
605 many-to-many relationship.
607 It doesn't matter which model gets the ``ManyToManyField``, but you only need
608 it in one of the models -- not in both.
610 Generally, ``ManyToManyField`` instances should go in the object that's going
611 to be edited in the admin. In the above example, ``toppings`` is in ``Pizza``
612 (rather than ``Topping`` having a ``pizzas`` ``ManyToManyField`` ) because it's
613 more natural to think about a ``Pizza`` having toppings than a topping being on
614 multiple pizzas. The way it's set up above, the ``Pizza`` admin form would let
615 users select the toppings.
617 See the `Many-to-many relationship model example`_ for a full example.
619 .. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
621 ``ManyToManyField`` objects take a number of extra arguments for defining how
622 the relationship should work. All are optional:
624 ======================= ============================================================
626 ======================= ============================================================
627 ``related_name`` See the description of ``related_name`` in
628 ``ForeignKey`` above.
630 ``filter_interface`` Use a nifty unobtrusive Javascript "filter" interface
631 instead of the usability-challenged ``<select multiple>``
632 in the admin form for this object. The value should be
633 ``meta.HORIZONTAL`` or ``meta.VERTICAL`` (i.e.
634 should the interface be stacked horizontally or
637 ``limit_choices_to`` See the description under ``ForeignKey`` above.
639 ``singular`` The singular name of the field. Use to name the ``get_*``
640 methods: in the example above, Django gives the ``Pizza``
641 objects a ``get_topping_list()`` method, where ``topping``
642 is the default ``singular`` value derived from the lowercase
643 version of the class being linked to. Use the singular
644 parameter to change this, which is if you want one model to
645 have multiple ``ManyToMany`` relationships to another model.
646 ======================= ============================================================
648 One-to-one relationships
649 ~~~~~~~~~~~~~~~~~~~~~~~~
651 To define a one-to-one relationship, use ``OneToOneField``. You use it just
652 like any other ``Field`` type: by including it as a class attribute of your
655 This is most useful on the primary key of an object when that object "extends"
656 another object in some way.
658 ``OneToOneField`` requires a positional argument: The class to which the
661 For example, if you're building a database of "places", you would build pretty
662 standard stuff such as address, phone number, etc. in the database. Then, if you
663 wanted to build a database of restaurants on top of the places, instead of
664 repeating yourself and replicating those fields in the ``Restaurant`` model, you
665 could make ``Restaurant`` have a ``OneToOneField`` to ``Place`` (because a
666 restaurant "is-a" place).
668 This ``OneToOneField`` will actually replace the primary key ``id`` field
669 (since one-to-one relations share the same primary key), and has a few
670 differences in the admin interface:
672 * No ``Place`` selection interface is displayed on ``Restaurant`` pages.
673 There will be one (and only one) ``Restaurant`` for each ``Place``.
675 * On the ``Restaurant`` change list, every ``Place`` -- whether it has an
676 associated ``Restaurant`` or not -- will be displayed. Adding a
677 ``Restaurant`` to a ``Place`` just means filling out the required
678 ``Restaurant`` fields.
680 See the `One-to-one relationship model example`_ for a full example.
682 .. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
687 Give your model metadata by using an inner ``"class META"``, like so::
689 class Foo(meta.Model):
690 bar = meta.CharField(maxlength=30)
696 Model metadata is "anything that's not a field" -- ordering options, admin
699 Here's a list of all possible ``META`` options. No options are required. Adding
700 ``class META`` to a model is completely optional.
703 A ``meta.Admin`` object; see `Admin options`_. If this field is given, the
704 object will have an admin interface. If it isn't given, the object won't
708 The name of the database table to use for the module::
710 db_table = "pizza_orders"
712 If this isn't given, Django will use ``app_label + '_' + module_name``.
714 If your database table name is an SQL reserved word, or contains characters
715 that aren't allowed in Python variable names -- notably, the hyphen --
716 that's OK. Django quotes column and table names behind the scenes.
719 Names of extra exception subclasses to include in the generated module.
720 These exceptions are available from instance methods and from module-level
723 exceptions = ("DisgustingToppingsException", "BurntCrust")
726 The name of a ``DateField`` or ``DateTimeField``. If given, the module will
727 have a ``get_latest()`` function that fetches the "latest" object according
730 get_latest_by = "order_date"
732 See `Getting the "latest" object`_ for a full example.
734 .. _Getting the "latest" object: http://www.djangoproject.com/documentation/models/get_latest/
737 A dictionary of names/values to use as extra module-level constants::
740 'MEAT_TYPE_PEPPERONI' : 1,
741 'MEAT_TYPE_SAUSAGE' : 2,
745 The name of the module::
747 module_name = "pizza_orders"
749 If this isn't given, Django will use a lowercased version of the class
750 name, plus ``"s"``. This "poor man's pluralization" is intentional: Any
751 other level of magic pluralization would get confusing.
753 ``order_with_respect_to``
754 Marks this object as "orderable" with respect to the given field. This is
755 almost always used with related objects to allow them to be ordered with
756 respect to a parent object. For example, if a ``PizzaToppping`` relates to
757 a ``Pizza`` object, you might use::
759 order_with_respect_to = 'pizza'
761 to allow the toppings to be ordered with respect to the associated pizza.
764 The default ordering for the object, for use by ``get_list`` and the admin::
766 ordering = ['-order_date']
768 This is a tuple or list of strings. Each string is a field name with an
769 optional "-" prefix, which indicates descending order. Fields without a
770 leading "-" will be ordered ascending. Use the string "?" to order randomly.
772 See `Specifying ordering`_ for a full example.
774 .. _Specifying ordering: http://www.djangoproject.com/documentation/models/ordering/
777 Extra permissions to enter into the permissions table when creating this
778 object. Add, delete and change permissions are automatically created for
779 each object that has ``admin`` set. This example specifies an extra
780 permission, ``can_deliver_pizzas``::
782 permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
784 This is a list or tuple of 2-tuples in the format
785 ``(permission_code, human_readable_permission_name)``.
788 Sets of field names that, taken together, must be unique::
790 unique_together = (("driver", "restaurant"),)
792 This is a list of lists of fields that must be unique when considered
793 together. It's used in the Django admin and is enforced at the database
794 level (i.e., the appropriate ``UNIQUE`` statements are included in the
795 ``CREATE TABLE`` statement).
798 A human-readable name for the object, singular::
800 verbose_name = "pizza"
802 If this isn't given, Django will use a munged version of the class name:
803 ``CamelCase`` becomes ``camel case``.
805 ``verbose_name_plural``
806 The plural name for the object::
808 verbose_name_plural = "stories"
810 If this isn't given, Django will use ``verbose_name + "s"``.
815 The ``admin`` field in the model tells Django how to construct the admin
816 interface for the object. The field is an instance of the ``meta.Admin``
817 object, which takes the following parameters. All are optional.
820 To allow filtering of objects in the admin by date, set ``date_hierarchy``
821 to the name of the field to filter by::
823 date_hierarchy = 'order_date'
826 A list of fieldsets to display on the admin page. Each fieldset is a 2-tuple:
827 ``(name, field_options)``. The ``name`` is a string to name the field set,
828 and ``field_options`` is a dictionary of information about the fields to be
829 displayed in that fieldset. This dictionary has the following keys:
832 A tuple of field names to display in this fieldset. To display
833 multiple fields on the same line, wrap those fields in their
836 This key is required in the dictionary.
839 Extra CSS classes to apply to the fieldset. This is a simple
840 string. You can apply multiple classes by separating them with
843 Two useful classes defined by the default stylesheet are
844 ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
845 will be initially collapsed in the admin and replaced with a small
846 "click to expand" link. Fieldsets with the ``wide`` style will be
847 given extra horizontal space.
849 For example (taken from the ``django.contrib.flatpages`` model)::
853 'fields': ('url', 'title', 'content', 'sites')
855 ('Advanced options', {
856 'classes': 'collapse',
857 'fields' : ('enable_comments', 'registration_required', 'template_name')
861 results in an admin that looks like:
863 .. image:: http://media.djangoproject.com/img/doc/flatfiles_admin.png
865 If ``fields`` isn't given but a model does define ``admin`` as a
866 ``meta.Admin`` object, Django will default to displaying each field that
867 isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in
868 the same order as the fields are defined in the model.
871 A list of strings representing URLs of JavaScript files to link into the
872 admin screen. This can be used to tweak a given type of admin page in JS or
873 to provide "quick links" to fill in default values for certain fields.
876 List of fields to display on the list page in the admin.
878 There are a few special cases that do other things besides displaying the
879 contents of the given fields:
881 * If the field given is a ``ForeignKey``, the ``repr()`` of the related
882 object will be displayed.
884 * ``ManyToManyField`` fields aren't supported, because that would
885 entail executing a separate SQL statement for each row in the table.
887 * If the field is a ``BooleanField``, a "on" or "off" icon will
888 be displayed instead of ``True`` or ``False``.
890 * If the field name is a method of the model, it'll be called, and the
891 output will be displayed. This method should have a
892 ``short_description`` function attribute, for use as the header for
895 * Use the string ``"__repr__"`` to output the representation of the
896 object, according to your model's ``__repr__()`` function. If you
897 don't define ``list_display``, Django will use the ``__repr__`` by
900 See the example below.
903 List of fields to filter by. Each field should either be a ``BooleanField``
904 or else a field with a ``ManyToOne`` relation.
906 Here's an example of how ``list_display`` and ``list_filter`` work (taken
907 from the ``auth.user`` model)::
909 list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
910 list_filter = ('is_staff', 'is_superuser'),
912 This results in a admin that looks like:
914 .. image:: http://media.djangoproject.com/img/doc/users_changelist.png
916 (This example also has ``search_fields`` defined; see below).
918 ``list_select_related``
919 Either ``True`` or ``False``. Default is ``False``. If ``True``, the admin
920 change list page will use the ``select_related`` database-API parameter in
921 its query that retrieves the list of items.
923 Note that Django will use ``select_related``, regardless of this setting,
924 if one of the ``list_display`` fields is a ``ForeignKey``.
927 A list or tuple (see the `META options`_, above) that gives a
928 different ordering for the admin change list. If this isn't given, the
929 model's default ordering will be used.
932 Enables a "save as" feature on object pages. Normally, objects have three
933 save options: "Save", "Save and continue editing" and "Save and add
934 another". If ``save_as`` is ``True``, "Save and add another" will be
935 replaced by a "Save as" button.
937 "Save as" means the object will be saved as a new object (with a new ID),
938 rather than the old object.
941 If this option is ``True``, object pages will have the save buttons across
942 the top as well as at the bottom of the page.
945 A list of field names to provide a text search for. These fields should,
946 obviously, be some kind of text field, such as ``CharField`` or
952 There are a number of methods you can define on model objects to control the
953 object's behavior. First, any methods you define will be available as methods
954 of object instances. For example::
956 class Pizza(meta.Model):
959 def is_disgusting(self):
960 return "anchovies" in [topping.name for topping in self.get_topping_list()]
962 Now, every ``Pizza`` object will have a ``is_disgusting()`` method.
964 Note that the scope of custom methods is modified to be the same as the module
965 scope. These methods do NOT have access to globals within your model's module.
966 Additionally, custom methods have access to a few commonly-used objects for
969 * The ``datetime`` module from Python's standard library.
970 * The ``db`` object from ``django.core.db``. This represents the database
971 connection, so you can do custom queries via a cursor object. See
972 "Executing custom SQL" below.
974 See `Giving models custom methods`_ for a full example.
976 .. _Giving models custom methods: http://www.djangoproject.com/documentation/models/custom_methods/
978 A few object methods have special meaning:
981 Django uses ``repr(obj)`` in a number of places, most notably as the value
982 inserted into a template when it displays an object. Thus, you should always
983 return a nice, human-readable string for the object's ``__repr__``.
985 Although defining ``__repr__()`` isn't required, it's strongly encouraged.
987 See `Adding repr`_ for a full example.
989 .. _Adding repr: http://www.djangoproject.com/documentation/models/repr/
992 Define a ``get_absolute_url`` method to tell Django how to calculate the
993 URL for an object. For example::
995 def get_absolute_url(self):
996 return "/pizzas/%i/" % self.id
998 Django uses this in its admin interface. If an object defines
999 ``get_absolute_url``, the object detail page will have a "View on site"
1000 link that will jump you directly to the object's public view.
1002 It's good practice to use ``get_absolute_url()`` in templates, instead of
1003 hard-coding your objects' URLs.
1006 This method is called just before an object is saved to the database. For
1007 example, you can use it to calculate aggregate values from other fields
1008 before the object is saved.
1010 See `Adding hooks before/after saving and deleting`_ for a full example.
1012 .. _Adding hooks before/after saving and deleting: http://www.djangoproject.com/documentation/models/save_delete_hooks/
1015 This method is called just after the object is saved to the database. This
1016 could be used to update other tables, update cached information, etc.
1019 Like ``_pre_save``, but for deletion.
1022 Like ``_post_save``, but for deletion.
1024 Module-level methods
1025 --------------------
1027 Since each data class effectively turns into a "magic" Python module under
1028 ``django.models``, there are times you'll want to write methods that live in
1029 that module. Any model method that begins with "_module_" is turned into a
1030 module-level function::
1032 class Pizza(meta.Model):
1035 def _module_get_pizzas_to_deliver():
1036 return get_list(delivered__exact=False)
1038 This will make the top-level ``pizzas`` module have a ``get_pizzas_to_deliver()``
1041 >>> from django.models.pizza_hut import pizzas
1042 >>> pizzas.get_pizzas_to_deliver()
1045 Note that the scope of these methods is modified to be the same as the module
1046 scope. These methods do NOT have access to globals within your model's module.
1051 Similarly, you can add methods to the object's manipulators by defining methods
1052 that being with "_manipulator_". This is most useful for providing custom
1053 validators for certain fields, because manipulators automatically call any
1054 method that begins with "validate"::
1056 class Pizza(meta.Model):
1059 def _manipulator_validate_customer_id(self, field_data, all_data):
1060 from django.core import validators
1061 from django.conf.settings import BAD_CUSTOMER_IDS
1063 if int(field_data) in BAD_CUSTOMER_IDS:
1064 raise validators.ValidationError, "We don't deliver to this customer."
1066 Executing custom SQL
1067 --------------------
1069 Feel free to write custom SQL statements in custom model methods and
1070 module-level methods. Each custom method automatically has access to the
1071 variable ``db``, which is the current database connection. To use it, call
1072 ``db.cursor()`` to get a cursor object. Then, call ``cursor.execute(sql, [params])``
1073 to execute the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return
1074 the resulting rows. Example::
1076 def my_custom_sql(self):
1077 cursor = db.cursor()
1078 cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
1079 row = cursor.fetchone()
1082 If your custom SQL statement alters the data in your database -- for example,
1083 via a ``DELETE`` or ``UPDATE`` -- you'll need to call ``db.commit()``. Example::
1085 def my_custom_sql2(self):
1086 cursor = db.cursor()
1087 cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz])
1090 ``db`` and ``cursor`` simply use the standard `Python DB-API`_. If you're not
1091 familiar with the Python DB-API, note that the SQL statement in
1092 ``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters
1093 directly within the SQL. If you use this technique, the underlying database
1094 library will automatically add quotes and escaping to your parameter(s) as
1097 .. _Python DB-API: http://www.python.org/peps/pep-0249.html
1102 Once you've defined a model, you'll need to "enable" it in Django. This section
1103 explains how Django searches for available models.
1105 Save your models in a normal Python module. Put this module within a package
1106 called "models", which should itself be a subpackage of some other package on
1107 your Python path. The ``__init__.py`` in your ``models`` package should contain
1108 an ``__all__`` variable that is set to a list of all model module names within
1109 the ``models`` directory.
1111 If this sounds confusing, just use ``django-admin.py startapp`` -- it'll create
1112 the proper directory structure and ``__init__.py`` files. (See the
1113 `django-admin.py documentation`_ .)
1115 For example, if you save your models in a module called ``mymodels.py``, here's
1116 a directory layout you might use::
1119 __init__.py # Empty file
1121 __init__.py # Contains "__all__ = ['mymodels']"
1122 mymodels.py # Contains your models
1124 Then, you'll have to tell Django that the ``myapp`` application is installed.
1125 Do this by editing your settings file and adding ``"myapp"`` to the
1126 ``INSTALLED_APPS`` tuple.
1128 Again, if this sounds confusing, use ``django-admin.py startapp`` to take care
1129 of package creation for you. This documentation exists only to explain how
1132 Once you've added your app to ``INSTALLED_APPS``, you can open a Python
1133 interactive interpreter and play with your model::
1135 >>> from django.models.mymodels import pizzas
1136 >>> pizzas.get_list()
1138 Note that the import is from ``django.models``, not ``myapp.models``. Django
1139 creates a "magic" module within ``django.models`` for every installed
1140 application. Each of those magic modules has a dynamic API. See the
1141 `database API reference`_ for full information on how to use this API.
1143 .. admonition:: Why is the INSTALLED_APPS setting necessary?
1145 Model relationships work both ways, and the dynamically-generated Django API
1146 creates API lookups in both directions. Thus, for Django to figure out all
1147 the other models related to a particular model, it has to know the complete
1148 spectrum of installed apps.
1150 .. _`django-admin.py documentation`: http://www.djangoproject.com/documentation/django_admin/
1151 .. _`database API reference`: http://www.djangoproject.com/documentation/db_api/
1156 It's perfectly OK to relate a model to one from another module. To do this,
1157 just import the model module at the top of your model module, like so::
1159 from django.models import core
1161 Make sure you're importing from ``django.models``, not directly from your model
1164 Then, just refer to the other model class wherever needed. For example::
1166 class MyModel(meta.Model):
1168 sites = meta.ManyToManyField(core.Site)
1170 Models in multiple files
1171 ========================
1173 If you want to have multiple model modules in a ``"models"`` directory, make
1174 sure you edit ``"models/__init__.py"`` and add the name of your model module
1175 to the ``__all__`` variable. If your ``models`` package doesn't have your model
1176 module in ``__all__``, Django won't see any of the models in that module.