5 .. module:: django.db.models
7 A model is the single, definitive source of data about your data. It contains
8 the essential fields and behaviors of the data you're storing. Generally, each
9 model maps to a single database table.
13 * Each model is a Python class that subclasses
14 :class:`django.db.models.Model`.
16 * Each attribute of the model represents a database field.
18 * With all of this, Django gives you an automatically-generated
19 database-access API; see :doc:`/topics/db/queries`.
25 This example model defines a ``Person``, which has a ``first_name`` and
28 from django.db import models
30 class Person(models.Model):
31 first_name = models.CharField(max_length=30)
32 last_name = models.CharField(max_length=30)
34 ``first_name`` and ``last_name`` are fields_ of the model. Each field is
35 specified as a class attribute, and each attribute maps to a database column.
37 The above ``Person`` model would create a database table like this:
41 CREATE TABLE myapp_person (
42 "id" serial NOT NULL PRIMARY KEY,
43 "first_name" varchar(30) NOT NULL,
44 "last_name" varchar(30) NOT NULL
49 * The name of the table, ``myapp_person``, is automatically derived from
50 some model metadata but can be overridden. See :ref:`table-names` for more
53 * An ``id`` field is added automatically, but this behavior can be
54 overridden. See :ref:`automatic-primary-key-fields`.
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 :doc:`settings file </topics/settings>`.
63 Once you have defined your models, you need to tell Django you're going to *use*
64 those models. Do this by editing your settings file and changing the
65 :setting:`INSTALLED_APPS` setting to add the name of the module that contains
68 For example, if the models for your application live in the module
69 ``mysite.myapp.models`` (the package structure that is created for an
70 application by the :djadmin:`manage.py startapp <startapp>` script),
71 :setting:`INSTALLED_APPS` should read, in part::
79 When you add new apps to :setting:`INSTALLED_APPS`, be sure to run
80 :djadmin:`manage.py syncdb <syncdb>`.
85 The most important part of a model -- and the only required part of a model --
86 is the list of database fields it defines. Fields are specified by class
87 attributes. Be careful not to choose field names that conflict with the
88 :doc:`models API </ref/models/instances>` like ``clean``, ``save``, or
93 class Musician(models.Model):
94 first_name = models.CharField(max_length=50)
95 last_name = models.CharField(max_length=50)
96 instrument = models.CharField(max_length=100)
98 class Album(models.Model):
99 artist = models.ForeignKey(Musician)
100 name = models.CharField(max_length=100)
101 release_date = models.DateField()
102 num_stars = models.IntegerField()
107 Each field in your model should be an instance of the appropriate
108 :class:`~django.db.models.Field` class. Django uses the field class types to
109 determine a few things:
111 * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
113 * The default :doc:`widget </ref/forms/widgets>` to use when rendering a form
114 field (e.g. ``<input type="text">``, ``<select>``).
116 * The minimal validation requirements, used in Django's admin and in
117 automatically-generated forms.
119 Django ships with dozens of built-in field types; you can find the complete list
120 in the :ref:`model field reference <model-field-types>`. You can easily write
121 your own fields if Django's built-in ones don't do the trick; see
122 :doc:`/howto/custom-model-fields`.
127 Each field takes a certain set of field-specific arguments (documented in the
128 :ref:`model field reference <model-field-types>`). For example,
129 :class:`~django.db.models.CharField` (and its subclasses) require a
130 :attr:`~django.db.models.CharField.max_length` argument which specifies the size
131 of the ``VARCHAR`` database field used to store the data.
133 There's also a set of common arguments available to all field types. All are
134 optional. They're fully explained in the :ref:`reference
135 <common-model-field-options>`, but here's a quick summary of the most often-used
139 If ``True``, Django will store empty values as ``NULL`` in the database.
140 Default is ``False``.
143 If ``True``, the field is allowed to be blank. Default is ``False``.
145 Note that this is different than :attr:`~Field.null`.
146 :attr:`~Field.null` is purely database-related, whereas
147 :attr:`~Field.blank` is validation-related. If a field has
148 :attr:`blank=True <Field.blank>`, form validation will
149 allow entry of an empty value. If a field has :attr:`blank=False
150 <Field.blank>`, the field will be required.
152 :attr:`~Field.choices`
153 An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
154 this field. If this is given, the default form widget will be a select box
155 instead of the standard text field and will limit choices to the choices
158 A choices list looks like this::
160 YEAR_IN_SCHOOL_CHOICES = (
161 (u'FR', u'Freshman'),
162 (u'SO', u'Sophomore'),
165 (u'GR', u'Graduate'),
168 The first element in each tuple is the value that will be stored in the
169 database, the second element will be displayed by the default form widget
170 or in a ModelChoiceField. Given an instance of a model object, the
171 display value for a choices field can be accessed using the
172 ``get_FOO_display`` method. For example::
174 from django.db import models
176 class Person(models.Model):
182 name = models.CharField(max_length=60)
183 shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
187 >>> p = Person(name="Fred Flintstone", shirt_size="L")
191 >>> p.get_shirt_size_display()
194 :attr:`~Field.default`
195 The default value for the field. This can be a value or a callable
196 object. If callable it will be called every time a new object is
199 :attr:`~Field.help_text`
200 Extra "help" text to be displayed with the form widget. It's useful for
201 documentation even if your field isn't used on a form.
203 :attr:`~Field.primary_key`
204 If ``True``, this field is the primary key for the model.
206 If you don't specify :attr:`primary_key=True <Field.primary_key>` for
207 any fields in your model, Django will automatically add an
208 :class:`IntegerField` to hold the primary key, so you don't need to set
209 :attr:`primary_key=True <Field.primary_key>` on any of your fields
210 unless you want to override the default primary-key behavior. For more,
211 see :ref:`automatic-primary-key-fields`.
213 :attr:`~Field.unique`
214 If ``True``, this field must be unique throughout the table.
216 Again, these are just short descriptions of the most common field options. Full
217 details can be found in the :ref:`common model field option reference
218 <common-model-field-options>`.
220 .. _automatic-primary-key-fields:
222 Automatic primary key fields
223 ----------------------------
225 By default, Django gives each model the following field::
227 id = models.AutoField(primary_key=True)
229 This is an auto-incrementing primary key.
231 If you'd like to specify a custom primary key, just specify
232 :attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
233 sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
236 Each model requires exactly one field to have :attr:`primary_key=True
237 <Field.primary_key>`.
239 .. _verbose-field-names:
244 Each field type, except for :class:`~django.db.models.ForeignKey`,
245 :class:`~django.db.models.ManyToManyField` and
246 :class:`~django.db.models.OneToOneField`, takes an optional first positional
247 argument -- a verbose name. If the verbose name isn't given, Django will
248 automatically create it using the field's attribute name, converting underscores
251 In this example, the verbose name is ``"person's first name"``::
253 first_name = models.CharField("person's first name", max_length=30)
255 In this example, the verbose name is ``"first name"``::
257 first_name = models.CharField(max_length=30)
259 :class:`~django.db.models.ForeignKey`,
260 :class:`~django.db.models.ManyToManyField` and
261 :class:`~django.db.models.OneToOneField` require the first argument to be a
262 model class, so use the :attr:`~Field.verbose_name` keyword argument::
264 poll = models.ForeignKey(Poll, verbose_name="the related poll")
265 sites = models.ManyToManyField(Site, verbose_name="list of sites")
266 place = models.OneToOneField(Place, verbose_name="related place")
268 The convention is not to capitalize the first letter of the
269 :attr:`~Field.verbose_name`. Django will automatically capitalize the first
270 letter where it needs to.
275 Clearly, the power of relational databases lies in relating tables to each
276 other. Django offers ways to define the three most common types of database
277 relationships: many-to-one, many-to-many and one-to-one.
279 Many-to-one relationships
280 ~~~~~~~~~~~~~~~~~~~~~~~~~
282 To define a many-to-one relationship, use :class:`django.db.models.ForeignKey`.
283 You use it just like any other :class:`~django.db.models.Field` type: by
284 including it as a class attribute of your model.
286 :class:`~django.db.models.ForeignKey` requires a positional argument: the class
287 to which the model is related.
289 For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
290 ``Manufacturer`` makes multiple cars but each ``Car`` only has one
291 ``Manufacturer`` -- use the following definitions::
293 class Manufacturer(models.Model):
296 class Car(models.Model):
297 manufacturer = models.ForeignKey(Manufacturer)
300 You can also create :ref:`recursive relationships <recursive-relationships>` (an
301 object with a many-to-one relationship to itself) and :ref:`relationships to
302 models not yet defined <lazy-relationships>`; see :ref:`the model field
303 reference <ref-foreignkey>` for details.
305 It's suggested, but not required, that the name of a
306 :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
307 above) be the name of the model, lowercase. You can, of course, call the field
308 whatever you want. For example::
310 class Car(models.Model):
311 company_that_makes_it = models.ForeignKey(Manufacturer)
316 :class:`~django.db.models.ForeignKey` fields accept a number of extra
317 arguments which are explained in :ref:`the model field reference
318 <foreign-key-arguments>`. These options help define how the relationship
319 should work; all are optional.
321 For details on accessing backwards-related objects, see the
322 :ref:`Following relationships backward example <backwards-related-objects>`.
324 For sample code, see the :doc:`Many-to-one relationship model example
325 </topics/db/examples/many_to_one>`.
327 Many-to-many relationships
328 ~~~~~~~~~~~~~~~~~~~~~~~~~~
330 To define a many-to-many relationship, use
331 :class:`~django.db.models.ManyToManyField`. You use it just like any other
332 :class:`~django.db.models.Field` type: by including it as a class attribute of
335 :class:`~django.db.models.ManyToManyField` requires a positional argument: the
336 class to which the model is related.
338 For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
339 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
340 -- here's how you'd represent that::
342 class Topping(models.Model):
345 class Pizza(models.Model):
347 toppings = models.ManyToManyField(Topping)
349 As with :class:`~django.db.models.ForeignKey`, you can also create
350 :ref:`recursive relationships <recursive-relationships>` (an object with a
351 many-to-many relationship to itself) and :ref:`relationships to models not yet
352 defined <lazy-relationships>`; see :ref:`the model field reference
353 <ref-manytomany>` for details.
355 It's suggested, but not required, that the name of a
356 :class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)
357 be a plural describing the set of related model objects.
359 It doesn't matter which model has the
360 :class:`~django.db.models.ManyToManyField`, but you should only put it in one
361 of the models -- not both.
363 Generally, :class:`~django.db.models.ManyToManyField` instances should go in
364 the object that's going to be edited on a form. In the above example,
365 ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a ``pizzas``
366 :class:`~django.db.models.ManyToManyField` ) because it's more natural to think
367 about a pizza having toppings than a topping being on multiple pizzas. The way
368 it's set up above, the ``Pizza`` form would let users select the toppings.
372 See the :doc:`Many-to-many relationship model example
373 </topics/db/examples/many_to_many>` for a full example.
375 :class:`~django.db.models.ManyToManyField` fields also accept a number of
376 extra arguments which are explained in :ref:`the model field reference
377 <manytomany-arguments>`. These options help define how the relationship
378 should work; all are optional.
380 .. _intermediary-manytomany:
382 Extra fields on many-to-many relationships
383 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
385 When you're only dealing with simple many-to-many relationships such as
386 mixing and matching pizzas and toppings, a standard :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes
387 you may need to associate data with the relationship between two models.
389 For example, consider the case of an application tracking the musical groups
390 which musicians belong to. There is a many-to-many relationship between a person
391 and the groups of which they are a member, so you could use a
392 :class:`~django.db.models.ManyToManyField` to represent this relationship.
393 However, there is a lot of detail about the membership that you might want to
394 collect, such as the date at which the person joined the group.
396 For these situations, Django allows you to specify the model that will be used
397 to govern the many-to-many relationship. You can then put extra fields on the
398 intermediate model. The intermediate model is associated with the
399 :class:`~django.db.models.ManyToManyField` using the
400 :attr:`through <ManyToManyField.through>` argument to point to the model
401 that will act as an intermediary. For our musician example, the code would look
402 something like this::
404 class Person(models.Model):
405 name = models.CharField(max_length=128)
407 def __unicode__(self):
410 class Group(models.Model):
411 name = models.CharField(max_length=128)
412 members = models.ManyToManyField(Person, through='Membership')
414 def __unicode__(self):
417 class Membership(models.Model):
418 person = models.ForeignKey(Person)
419 group = models.ForeignKey(Group)
420 date_joined = models.DateField()
421 invite_reason = models.CharField(max_length=64)
423 When you set up the intermediary model, you explicitly specify foreign
424 keys to the models that are involved in the ManyToMany relation. This
425 explicit declaration defines how the two models are related.
427 There are a few restrictions on the intermediate model:
429 * Your intermediate model must contain one - and *only* one - foreign key
430 to the target model (this would be ``Person`` in our example). If you
431 have more than one foreign key, a validation error will be raised.
433 * Your intermediate model must contain one - and *only* one - foreign key
434 to the source model (this would be ``Group`` in our example). If you
435 have more than one foreign key, a validation error will be raised.
437 * The only exception to this is a model which has a many-to-many
438 relationship to itself, through an intermediary model. In this
439 case, two foreign keys to the same model are permitted, but they
440 will be treated as the two (different) sides of the many-to-many
443 * When defining a many-to-many relationship from a model to
444 itself, using an intermediary model, you *must* use
445 :attr:`symmetrical=False <ManyToManyField.symmetrical>` (see
446 :ref:`the model field reference <manytomany-arguments>`).
448 Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
449 your intermediary model (``Membership``, in this case), you're ready to start
450 creating some many-to-many relationships. You do this by creating instances of
451 the intermediate model::
453 >>> ringo = Person.objects.create(name="Ringo Starr")
454 >>> paul = Person.objects.create(name="Paul McCartney")
455 >>> beatles = Group.objects.create(name="The Beatles")
456 >>> m1 = Membership(person=ringo, group=beatles,
457 ... date_joined=date(1962, 8, 16),
458 ... invite_reason= "Needed a new drummer.")
460 >>> beatles.members.all()
461 [<Person: Ringo Starr>]
462 >>> ringo.group_set.all()
463 [<Group: The Beatles>]
464 >>> m2 = Membership.objects.create(person=paul, group=beatles,
465 ... date_joined=date(1960, 8, 1),
466 ... invite_reason= "Wanted to form a band.")
467 >>> beatles.members.all()
468 [<Person: Ringo Starr>, <Person: Paul McCartney>]
470 Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
471 or assignment (i.e., ``beatles.members = [...]``) to create relationships::
474 >>> beatles.members.add(john)
476 >>> beatles.members.create(name="George Harrison")
477 # AND NEITHER WILL THIS
478 >>> beatles.members = [john, paul, ringo, george]
480 Why? You can't just create a relationship between a ``Person`` and a ``Group``
481 - you need to specify all the detail for the relationship required by the
482 ``Membership`` model. The simple ``add``, ``create`` and assignment calls
483 don't provide a way to specify this extra detail. As a result, they are
484 disabled for many-to-many relationships that use an intermediate model.
485 The only way to create this type of relationship is to create instances of the
488 The :meth:`~django.db.models.fields.related.RelatedManager.remove` method is
489 disabled for similar reasons. However, the
490 :meth:`~django.db.models.fields.related.RelatedManager.clear` method can be
491 used to remove all many-to-many relationships for an instance::
493 # Beatles have broken up
494 >>> beatles.members.clear()
496 Once you have established the many-to-many relationships by creating instances
497 of your intermediate model, you can issue queries. Just as with normal
498 many-to-many relationships, you can query using the attributes of the
499 many-to-many-related model::
501 # Find all the groups with a member whose name starts with 'Paul'
502 >>> Group.objects.filter(members__name__startswith='Paul')
503 [<Group: The Beatles>]
505 As you are using an intermediate model, you can also query on its attributes::
507 # Find all the members of the Beatles that joined after 1 Jan 1961
508 >>> Person.objects.filter(
509 ... group__name='The Beatles',
510 ... membership__date_joined__gt=date(1961,1,1))
511 [<Person: Ringo Starr]
513 If you need to access a membership's information you may do so by directly
514 querying the ``Membership`` model::
516 >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
517 >>> ringos_membership.date_joined
518 datetime.date(1962, 8, 16)
519 >>> ringos_membership.invite_reason
520 u'Needed a new drummer.'
522 Another way to access the same information is by querying the
523 :ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a
526 >>> ringos_membership = ringo.membership_set.get(group=beatles)
527 >>> ringos_membership.date_joined
528 datetime.date(1962, 8, 16)
529 >>> ringos_membership.invite_reason
530 u'Needed a new drummer.'
533 One-to-one relationships
534 ~~~~~~~~~~~~~~~~~~~~~~~~
536 To define a one-to-one relationship, use
537 :class:`~django.db.models.OneToOneField`. You use it just like any other
538 ``Field`` type: by including it as a class attribute of your model.
540 This is most useful on the primary key of an object when that object "extends"
541 another object in some way.
543 :class:`~django.db.models.OneToOneField` requires a positional argument: the
544 class to which the model is related.
546 For example, if you were building a database of "places", you would
547 build pretty standard stuff such as address, phone number, etc. in the
548 database. Then, if you wanted to build a database of restaurants on
549 top of the places, instead of repeating yourself and replicating those
550 fields in the ``Restaurant`` model, you could make ``Restaurant`` have
551 a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
552 restaurant "is a" place; in fact, to handle this you'd typically use
553 :ref:`inheritance <model-inheritance>`, which involves an implicit
554 one-to-one relation).
556 As with :class:`~django.db.models.ForeignKey`, a
557 :ref:`recursive relationship <recursive-relationships>`
559 :ref:`references to as-yet undefined models <lazy-relationships>`
560 can be made; see :ref:`the model field reference <ref-onetoone>` for details.
564 See the :doc:`One-to-one relationship model example
565 </topics/db/examples/one_to_one>` for a full example.
567 :class:`~django.db.models.OneToOneField` fields also accept one optional argument
568 described in the :ref:`model field reference <ref-onetoone>`.
570 :class:`~django.db.models.OneToOneField` classes used to automatically become
571 the primary key on a model. This is no longer true (although you can manually
572 pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
573 Thus, it's now possible to have multiple fields of type
574 :class:`~django.db.models.OneToOneField` on a single model.
579 It's perfectly OK to relate a model to one from another app. To do this,
580 import the related model at the top of the model that holds your model. Then,
581 just refer to the other model class wherever needed. For example::
583 from geography.models import ZipCode
585 class Restaurant(models.Model):
587 zip_code = models.ForeignKey(ZipCode)
589 Field name restrictions
590 -----------------------
592 Django places only two restrictions on model field names:
594 1. A field name cannot be a Python reserved word, because that would result
595 in a Python syntax error. For example::
597 class Example(models.Model):
598 pass = models.IntegerField() # 'pass' is a reserved word!
600 2. A field name cannot contain more than one underscore in a row, due to
601 the way Django's query lookup syntax works. For example::
603 class Example(models.Model):
604 foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
606 These limitations can be worked around, though, because your field name doesn't
607 necessarily have to match your database column name. See the
608 :attr:`~Field.db_column` option.
610 SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
611 model field names, because Django escapes all database table names and column
612 names in every underlying SQL query. It uses the quoting syntax of your
613 particular database engine.
618 If one of the existing model fields cannot be used to fit your purposes, or if
619 you wish to take advantage of some less common database column types, you can
620 create your own field class. Full coverage of creating your own fields is
621 provided in :doc:`/howto/custom-model-fields`.
628 Give your model metadata by using an inner ``class Meta``, like so::
630 class Ox(models.Model):
631 horn_length = models.IntegerField()
634 ordering = ["horn_length"]
635 verbose_name_plural = "oxen"
637 Model metadata is "anything that's not a field", such as ordering options
638 (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
639 human-readable singular and plural names (:attr:`~Options.verbose_name` and
640 :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
641 Meta`` to a model is completely optional.
643 A complete list of all possible ``Meta`` options can be found in the :doc:`model
644 option reference </ref/models/options>`.
651 Define custom methods on a model to add custom "row-level" functionality to your
652 objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
653 "table-wide" things, model methods should act on a particular model instance.
655 This is a valuable technique for keeping business logic in one place -- the
658 For example, this model has a few custom methods::
660 from django.contrib.localflavor.us.models import USStateField
662 class Person(models.Model):
663 first_name = models.CharField(max_length=50)
664 last_name = models.CharField(max_length=50)
665 birth_date = models.DateField()
666 address = models.CharField(max_length=100)
667 city = models.CharField(max_length=50)
668 state = USStateField() # Yes, this is America-centric...
670 def baby_boomer_status(self):
671 "Returns the person's baby-boomer status."
673 if datetime.date(1945, 8, 1) <= self.birth_date <= datetime.date(1964, 12, 31):
675 if self.birth_date < datetime.date(1945, 8, 1):
679 def is_midwestern(self):
680 "Returns True if this person is from the Midwest."
681 return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
683 def _get_full_name(self):
684 "Returns the person's full name."
685 return '%s %s' % (self.first_name, self.last_name)
686 full_name = property(_get_full_name)
688 The last method in this example is a :term:`property`.
690 The :doc:`model instance reference </ref/models/instances>` has a complete list
691 of :ref:`methods automatically given to each model <model-instance-methods>`.
692 You can override most of these -- see `overriding predefined model methods`_,
693 below -- but there are a couple that you'll almost always want to define:
695 :meth:`~Model.__unicode__`
696 A Python "magic method" that returns a unicode "representation" of any
697 object. This is what Python and Django will use whenever a model
698 instance needs to be coerced and displayed as a plain string. Most
699 notably, this happens when you display an object in an interactive
700 console or in the admin.
702 You'll always want to define this method; the default isn't very helpful
705 :meth:`~Model.get_absolute_url`
706 This tells Django how to calculate the URL for an object. Django uses
707 this in its admin interface, and any time it needs to figure out a URL
710 Any object that has a URL that uniquely identifies it should define this
713 .. _overriding-model-methods:
715 Overriding predefined model methods
716 -----------------------------------
718 There's another set of :ref:`model methods <model-instance-methods>` that
719 encapsulate a bunch of database behavior that you'll want to customize. In
720 particular you'll often want to change the way :meth:`~Model.save` and
721 :meth:`~Model.delete` work.
723 You're free to override these methods (and any other model method) to alter
726 A classic use-case for overriding the built-in methods is if you want something
727 to happen whenever you save an object. For example (see
728 :meth:`~Model.save` for documentation of the parameters it accepts)::
730 class Blog(models.Model):
731 name = models.CharField(max_length=100)
732 tagline = models.TextField()
734 def save(self, *args, **kwargs):
736 super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
739 You can also prevent saving::
741 class Blog(models.Model):
742 name = models.CharField(max_length=100)
743 tagline = models.TextField()
745 def save(self, *args, **kwargs):
746 if self.name == "Yoko Ono's blog":
747 return # Yoko shall never have her own blog!
749 super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
751 It's important to remember to call the superclass method -- that's
752 that ``super(Blog, self).save(*args, **kwargs)`` business -- to ensure
753 that the object still gets saved into the database. If you forget to
754 call the superclass method, the default behavior won't happen and the
755 database won't get touched.
757 It's also important that you pass through the arguments that can be
758 passed to the model method -- that's what the ``*args, **kwargs`` bit
759 does. Django will, from time to time, extend the capabilities of
760 built-in model methods, adding new arguments. If you use ``*args,
761 **kwargs`` in your method definitions, you are guaranteed that your
762 code will automatically support those arguments when they are added.
764 .. admonition:: Overridden model methods are not called on bulk operations
766 Note that the :meth:`~Model.delete()` method for an object is not
767 necessarily called when :ref:`deleting objects in bulk using a
768 QuerySet<topics-db-queries-delete>`. To ensure customized delete logic
769 gets executed, you can use :data:`~django.db.models.signals.pre_delete`
770 and/or :data:`~django.db.models.signals.post_delete` signals.
772 Unfortunately, there isn't a workaround when
773 :meth:`creating<django.db.models.query.QuerySet.bulk_create>` or
774 :meth:`updating<django.db.models.query.QuerySet.update>` objects in bulk,
775 since none of :meth:`~Model.save()`,
776 :data:`~django.db.models.signals.pre_save`, and
777 :data:`~django.db.models.signals.post_save` are called.
782 Another common pattern is writing custom SQL statements in model methods and
783 module-level methods. For more details on using raw SQL, see the documentation
784 on :doc:`using raw SQL</topics/db/sql>`.
786 .. _model-inheritance:
791 Model inheritance in Django works almost identically to the way normal
792 class inheritance works in Python. The only decision you have to make
793 is whether you want the parent models to be models in their own right
794 (with their own database tables), or if the parents are just holders
795 of common information that will only be visible through the child
798 There are three styles of inheritance that are possible in Django.
800 1. Often, you will just want to use the parent class to hold information that
801 you don't want to have to type out for each child model. This class isn't
802 going to ever be used in isolation, so :ref:`abstract-base-classes` are
804 2. If you're subclassing an existing model (perhaps something from another
805 application entirely) and want each model to have its own database table,
806 :ref:`multi-table-inheritance` is the way to go.
807 3. Finally, if you only want to modify the Python-level behavior of a model,
808 without changing the models fields in any way, you can use
811 .. _abstract-base-classes:
813 Abstract base classes
814 ---------------------
816 Abstract base classes are useful when you want to put some common
817 information into a number of other models. You write your base class
818 and put ``abstract=True`` in the :ref:`Meta <meta-options>`
819 class. This model will then not be used to create any database
820 table. Instead, when it is used as a base class for other models, its
821 fields will be added to those of the child class. It is an error to
822 have fields in the abstract base class with the same name as those in
823 the child (and Django will raise an exception).
827 class CommonInfo(models.Model):
828 name = models.CharField(max_length=100)
829 age = models.PositiveIntegerField()
834 class Student(CommonInfo):
835 home_group = models.CharField(max_length=5)
837 The ``Student`` model will have three fields: ``name``, ``age`` and
838 ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
839 model, since it is an abstract base class. It does not generate a database
840 table or have a manager, and cannot be instantiated or saved directly.
842 For many uses, this type of model inheritance will be exactly what you want.
843 It provides a way to factor out common information at the Python level, whilst
844 still only creating one database table per child model at the database level.
849 When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
850 inner class you declared in the base class available as an
851 attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
852 class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
853 extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
855 class CommonInfo(models.Model):
861 class Student(CommonInfo):
863 class Meta(CommonInfo.Meta):
864 db_table = 'student_info'
866 Django does make one adjustment to the :ref:`Meta <meta-options>` class of an abstract base
867 class: before installing the :ref:`Meta <meta-options>` attribute, it sets ``abstract=False``.
868 This means that children of abstract base classes don't automatically become
869 abstract classes themselves. Of course, you can make an abstract base class
870 that inherits from another abstract base class. You just need to remember to
871 explicitly set ``abstract=True`` each time.
873 Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
874 abstract base class. For example, including ``db_table`` would mean that all
875 the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
876 the same database table, which is almost certainly not what you want.
878 .. _abstract-related-name:
880 Be careful with ``related_name``
881 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
883 If you are using the :attr:`~django.db.models.ForeignKey.related_name` attribute on a ``ForeignKey`` or
884 ``ManyToManyField``, you must always specify a *unique* reverse name for the
885 field. This would normally cause a problem in abstract base classes, since the
886 fields on this class are included into each of the child classes, with exactly
887 the same values for the attributes (including :attr:`~django.db.models.ForeignKey.related_name`) each time.
889 .. versionchanged:: 1.2
891 To work around this problem, when you are using :attr:`~django.db.models.ForeignKey.related_name` in an
892 abstract base class (only), part of the name should contain
893 ``'%(app_label)s'`` and ``'%(class)s'``.
895 - ``'%(class)s'`` is replaced by the lower-cased name of the child class
896 that the field is used in.
897 - ``'%(app_label)s'`` is replaced by the lower-cased name of the app the child
898 class is contained within. Each installed application name must be unique
899 and the model class names within each app must also be unique, therefore the
900 resulting name will end up being different.
902 For example, given an app ``common/models.py``::
904 class Base(models.Model):
905 m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
916 Along with another app ``rare/models.py``::
918 from common.models import Base
923 The reverse name of the ``common.ChildA.m2m`` field will be
924 ``common_childa_related``, whilst the reverse name of the
925 ``common.ChildB.m2m`` field will be ``common_childb_related``, and finally the
926 reverse name of the ``rare.ChildB.m2m`` field will be ``rare_childb_related``.
927 It is up to you how you use the ``'%(class)s'`` and ``'%(app_label)s`` portion
928 to construct your related name, but if you forget to use it, Django will raise
929 errors when you validate your models (or run :djadmin:`syncdb`).
931 If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
932 attribute for a field in an abstract base class, the default reverse name will
933 be the name of the child class followed by ``'_set'``, just as it normally
934 would be if you'd declared the field directly on the child class. For example,
935 in the above code, if the :attr:`~django.db.models.ForeignKey.related_name`
936 attribute was omitted, the reverse name for the ``m2m`` field would be
937 ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``
940 .. _multi-table-inheritance:
942 Multi-table inheritance
943 -----------------------
945 The second type of model inheritance supported by Django is when each model in
946 the hierarchy is a model all by itself. Each model corresponds to its own
947 database table and can be queried and created individually. The inheritance
948 relationship introduces links between the child model and each of its parents
949 (via an automatically-created :class:`~django.db.models.OneToOneField`).
952 class Place(models.Model):
953 name = models.CharField(max_length=50)
954 address = models.CharField(max_length=80)
956 class Restaurant(Place):
957 serves_hot_dogs = models.BooleanField()
958 serves_pizza = models.BooleanField()
960 All of the fields of ``Place`` will also be available in ``Restaurant``,
961 although the data will reside in a different database table. So these are both
964 >>> Place.objects.filter(name="Bob's Cafe")
965 >>> Restaurant.objects.filter(name="Bob's Cafe")
967 If you have a ``Place`` that is also a ``Restaurant``, you can get from the
968 ``Place`` object to the ``Restaurant`` object by using the lower-case version
971 >>> p = Place.objects.get(id=12)
972 # If p is a Restaurant object, this will give the child class:
976 However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
977 created directly as a ``Place`` object or was the parent of some other class),
978 referring to ``p.restaurant`` would raise a Restaurant.DoesNotExist exception.
980 ``Meta`` and multi-table inheritance
981 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
983 In the multi-table inheritance situation, it doesn't make sense for a child
984 class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
985 have already been applied to the parent class and applying them again would
986 normally only lead to contradictory behavior (this is in contrast with the
987 abstract base class case, where the base class doesn't exist in its own
990 So a child model does not have access to its parent's :ref:`Meta
991 <meta-options>` class. However, there are a few limited cases where the child
992 inherits behavior from the parent: if the child does not specify an
993 :attr:`~django.db.models.Options.ordering` attribute or a
994 :attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit
995 these from its parent.
997 If the parent has an ordering and you don't want the child to have any natural
998 ordering, you can explicitly disable it::
1000 class ChildModel(ParentModel):
1003 # Remove parent's ordering effect
1006 Inheritance and reverse relations
1007 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1009 Because multi-table inheritance uses an implicit
1010 :class:`~django.db.models.OneToOneField` to link the child and
1011 the parent, it's possible to move from the parent down to the child,
1012 as in the above example. However, this uses up the name that is the
1013 default :attr:`~django.db.models.ForeignKey.related_name` value for
1014 :class:`~django.db.models.ForeignKey` and
1015 :class:`~django.db.models.ManyToManyField` relations. If you
1016 are putting those types of relations on a subclass of another model,
1017 you **must** specify the
1018 :attr:`~django.db.models.ForeignKey.related_name` attribute on each
1019 such field. If you forget, Django will raise an error when you run
1020 :djadmin:`validate` or :djadmin:`syncdb`.
1022 For example, using the above ``Place`` class again, let's create another
1023 subclass with a :class:`~django.db.models.ManyToManyField`::
1025 class Supplier(Place):
1026 # Must specify related_name on all relations.
1027 customers = models.ManyToManyField(Restaurant, related_name='provider')
1030 Specifying the parent link field
1031 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1033 As mentioned, Django will automatically create a
1034 :class:`~django.db.models.OneToOneField` linking your child
1035 class back any non-abstract parent models. If you want to control the
1036 name of the attribute linking back to the parent, you can create your
1037 own :class:`~django.db.models.OneToOneField` and set
1038 :attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`
1039 to indicate that your field is the link back to the parent class.
1046 When using :ref:`multi-table inheritance <multi-table-inheritance>`, a new
1047 database table is created for each subclass of a model. This is usually the
1048 desired behavior, since the subclass needs a place to store any additional
1049 data fields that are not present on the base class. Sometimes, however, you
1050 only want to change the Python behavior of a model -- perhaps to change the
1051 default manager, or add a new method.
1053 This is what proxy model inheritance is for: creating a *proxy* for the
1054 original model. You can create, delete and update instances of the proxy model
1055 and all the data will be saved as if you were using the original (non-proxied)
1056 model. The difference is that you can change things like the default model
1057 ordering or the default manager in the proxy, without having to alter the
1060 Proxy models are declared like normal models. You tell Django that it's a
1061 proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
1062 the ``Meta`` class to ``True``.
1064 For example, suppose you want to add a method to the standard
1065 :class:`~django.contrib.auth.models.User` model that will be used in your
1066 templates. You can do it like this::
1068 from django.contrib.auth.models import User
1074 def do_something(self):
1077 The ``MyUser`` class operates on the same database table as its parent
1078 :class:`~django.contrib.auth.models.User` class. In particular, any new
1079 instances of :class:`~django.contrib.auth.models.User` will also be accessible
1080 through ``MyUser``, and vice-versa::
1082 >>> u = User.objects.create(username="foobar")
1083 >>> MyUser.objects.get(username="foobar")
1086 You could also use a proxy model to define a different default ordering on a
1087 model. The standard :class:`~django.contrib.auth.models.User` model has no
1088 ordering defined on it (intentionally; sorting is expensive and we don't want
1089 to do it all the time when we fetch users). You might want to regularly order
1090 by the ``username`` attribute when you use the proxy. This is easy::
1092 class OrderedUser(User):
1094 ordering = ["username"]
1097 Now normal :class:`~django.contrib.auth.models.User` queries will be unordered
1098 and ``OrderedUser`` queries will be ordered by ``username``.
1100 QuerySets still return the model that was requested
1101 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1103 There is no way to have Django return, say, a ``MyUser`` object whenever you
1104 query for :class:`~django.contrib.auth.models.User` objects. A queryset for
1105 ``User`` objects will return those types of objects. The whole point of proxy
1106 objects is that code relying on the original ``User`` will use those and your
1107 own code can use the extensions you included (that no other code is relying on
1108 anyway). It is not a way to replace the ``User`` (or any other) model
1109 everywhere with something of your own creation.
1111 Base class restrictions
1112 ~~~~~~~~~~~~~~~~~~~~~~~
1114 A proxy model must inherit from exactly one non-abstract model class. You
1115 can't inherit from multiple non-abstract models as the proxy model doesn't
1116 provide any connection between the rows in the different database tables. A
1117 proxy model can inherit from any number of abstract model classes, providing
1118 they do *not* define any model fields.
1120 Proxy models inherit any ``Meta`` options that they don't define from their
1121 non-abstract model parent (the model they are proxying for).
1123 Proxy model managers
1124 ~~~~~~~~~~~~~~~~~~~~
1126 If you don't specify any model managers on a proxy model, it inherits the
1127 managers from its model parents. If you define a manager on the proxy model,
1128 it will become the default, although any managers defined on the parent
1129 classes will still be available.
1131 Continuing our example from above, you could change the default manager used
1132 when you query the ``User`` model like this::
1134 class NewManager(models.Manager):
1138 objects = NewManager()
1143 If you wanted to add a new manager to the Proxy, without replacing the
1144 existing default, you can use the techniques described in the :ref:`custom
1145 manager <custom-managers-and-inheritance>` documentation: create a base class
1146 containing the new managers and inherit that after the primary base class::
1148 # Create an abstract class for the new manager.
1149 class ExtraManagers(models.Model):
1150 secondary = NewManager()
1155 class MyUser(User, ExtraManagers):
1159 You probably won't need to do this very often, but, when you do, it's
1162 .. _proxy-vs-unmanaged-models:
1164 Differences between proxy inheritance and unmanaged models
1165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1167 Proxy model inheritance might look fairly similar to creating an unmanaged
1168 model, using the :attr:`~django.db.models.Options.managed` attribute on a
1169 model's ``Meta`` class. The two alternatives are not quite the same and it's
1170 worth considering which one you should use.
1172 One difference is that you can (and, in fact, must unless you want an empty
1173 model) specify model fields on models with ``Meta.managed=False``. You could,
1174 with careful setting of :attr:`Meta.db_table
1175 <django.db.models.Options.db_table>` create an unmanaged model that shadowed
1176 an existing model and add Python methods to it. However, that would be very
1177 repetitive and fragile as you need to keep both copies synchronized if you
1180 The other difference that is more important for proxy models, is how model
1181 managers are handled. Proxy models are intended to behave exactly like the
1182 model they are proxying for. So they inherit the parent model's managers,
1183 including the default manager. In the normal multi-table model inheritance
1184 case, children do not inherit managers from their parents as the custom
1185 managers aren't always appropriate when extra fields are involved. The
1186 :ref:`manager documentation <custom-managers-and-inheritance>` has more
1187 details about this latter case.
1189 When these two features were implemented, attempts were made to squash them
1190 into a single option. It turned out that interactions with inheritance, in
1191 general, and managers, in particular, made the API very complicated and
1192 potentially difficult to understand and use. It turned out that two options
1193 were needed in any case, so the current separation arose.
1195 So, the general rules are:
1197 1. If you are mirroring an existing model or database table and don't want
1198 all the original database table columns, use ``Meta.managed=False``.
1199 That option is normally useful for modeling database views and tables
1200 not under the control of Django.
1201 2. If you are wanting to change the Python-only behavior of a model, but
1202 keep all the same fields as in the original, use ``Meta.proxy=True``.
1203 This sets things up so that the proxy model is an exact copy of the
1204 storage structure of the original model when data is saved.
1206 Multiple inheritance
1207 --------------------
1209 Just as with Python's subclassing, it's possible for a Django model to inherit
1210 from multiple parent models. Keep in mind that normal Python name resolution
1211 rules apply. The first base class that a particular name (e.g. :ref:`Meta
1212 <meta-options>`) appears in will be the one that is used; for example, this
1213 means that if multiple parents contain a :ref:`Meta <meta-options>` class,
1214 only the first one is going to be used, and all others will be ignored.
1216 Generally, you won't need to inherit from multiple parents. The main use-case
1217 where this is useful is for "mix-in" classes: adding a particular extra
1218 field or method to every class that inherits the mix-in. Try to keep your
1219 inheritance hierarchies as simple and straightforward as possible so that you
1220 won't have to struggle to work out where a particular piece of information is
1223 Field name "hiding" is not permitted
1224 -------------------------------------
1226 In normal Python class inheritance, it is permissible for a child class to
1227 override any attribute from the parent class. In Django, this is not permitted
1228 for attributes that are :class:`~django.db.models.Field` instances (at
1229 least, not at the moment). If a base class has a field called ``author``, you
1230 cannot create another model field called ``author`` in any class that inherits
1231 from that base class.
1233 Overriding fields in a parent model leads to difficulties in areas such as
1234 initializing new instances (specifying which field is being initialized in
1235 ``Model.__init__``) and serialization. These are features which normal Python
1236 class inheritance doesn't have to deal with in quite the same way, so the
1237 difference between Django model inheritance and Python class inheritance isn't
1240 This restriction only applies to attributes which are
1241 :class:`~django.db.models.Field` instances. Normal Python attributes
1242 can be overridden if you wish. It also only applies to the name of the
1243 attribute as Python sees it: if you are manually specifying the database
1244 column name, you can have the same column name appearing in both a child and
1245 an ancestor model for multi-table inheritance (they are columns in two
1246 different database tables).
1248 Django will raise a :exc:`~django.core.exceptions.FieldError` if you override
1249 any model field in any ancestor model.