models.txt 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. ======
  2. Models
  3. ======
  4. .. module:: django.db.models
  5. A model is the single, definitive source of information about your data. It
  6. contains the essential fields and behaviors of the data you're storing.
  7. Generally, each model maps to a single database table.
  8. The basics:
  9. * Each model is a Python class that subclasses
  10. :class:`django.db.models.Model`.
  11. * Each attribute of the model represents a database field.
  12. * With all of this, Django gives you an automatically-generated
  13. database-access API; see :doc:`/topics/db/queries`.
  14. Quick example
  15. =============
  16. This example model defines a ``Person``, which has a ``first_name`` and
  17. ``last_name``::
  18. from django.db import models
  19. class Person(models.Model):
  20. first_name = models.CharField(max_length=30)
  21. last_name = models.CharField(max_length=30)
  22. ``first_name`` and ``last_name`` are fields_ of the model. Each field is
  23. specified as a class attribute, and each attribute maps to a database column.
  24. The above ``Person`` model would create a database table like this:
  25. .. code-block:: sql
  26. CREATE TABLE myapp_person (
  27. "id" serial NOT NULL PRIMARY KEY,
  28. "first_name" varchar(30) NOT NULL,
  29. "last_name" varchar(30) NOT NULL
  30. );
  31. Some technical notes:
  32. * The name of the table, ``myapp_person``, is automatically derived from
  33. some model metadata but can be overridden. See :ref:`table-names` for more
  34. details.
  35. * An ``id`` field is added automatically, but this behavior can be
  36. overridden. See :ref:`automatic-primary-key-fields`.
  37. * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
  38. syntax, but it's worth noting Django uses SQL tailored to the database
  39. backend specified in your :doc:`settings file </topics/settings>`.
  40. Using models
  41. ============
  42. Once you have defined your models, you need to tell Django you're going to *use*
  43. those models. Do this by editing your settings file and changing the
  44. :setting:`INSTALLED_APPS` setting to add the name of the module that contains
  45. your ``models.py``.
  46. For example, if the models for your application live in the module
  47. ``myapp.models`` (the package structure that is created for an
  48. application by the :djadmin:`manage.py startapp <startapp>` script),
  49. :setting:`INSTALLED_APPS` should read, in part::
  50. INSTALLED_APPS = (
  51. #...
  52. 'myapp',
  53. #...
  54. )
  55. When you add new apps to :setting:`INSTALLED_APPS`, be sure to run
  56. :djadmin:`manage.py migrate <migrate>`, optionally making migrations
  57. for them first with :djadmin:`manage.py makemigrations <makemigrations>`.
  58. Fields
  59. ======
  60. The most important part of a model -- and the only required part of a model --
  61. is the list of database fields it defines. Fields are specified by class
  62. attributes. Be careful not to choose field names that conflict with the
  63. :doc:`models API </ref/models/instances>` like ``clean``, ``save``, or
  64. ``delete``.
  65. Example::
  66. from django.db import models
  67. class Musician(models.Model):
  68. first_name = models.CharField(max_length=50)
  69. last_name = models.CharField(max_length=50)
  70. instrument = models.CharField(max_length=100)
  71. class Album(models.Model):
  72. artist = models.ForeignKey(Musician)
  73. name = models.CharField(max_length=100)
  74. release_date = models.DateField()
  75. num_stars = models.IntegerField()
  76. Field types
  77. -----------
  78. Each field in your model should be an instance of the appropriate
  79. :class:`~django.db.models.Field` class. Django uses the field class types to
  80. determine a few things:
  81. * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
  82. * The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a form
  83. field (e.g. ``<input type="text">``, ``<select>``).
  84. * The minimal validation requirements, used in Django's admin and in
  85. automatically-generated forms.
  86. Django ships with dozens of built-in field types; you can find the complete list
  87. in the :ref:`model field reference <model-field-types>`. You can easily write
  88. your own fields if Django's built-in ones don't do the trick; see
  89. :doc:`/howto/custom-model-fields`.
  90. Field options
  91. -------------
  92. Each field takes a certain set of field-specific arguments (documented in the
  93. :ref:`model field reference <model-field-types>`). For example,
  94. :class:`~django.db.models.CharField` (and its subclasses) require a
  95. :attr:`~django.db.models.CharField.max_length` argument which specifies the size
  96. of the ``VARCHAR`` database field used to store the data.
  97. There's also a set of common arguments available to all field types. All are
  98. optional. They're fully explained in the :ref:`reference
  99. <common-model-field-options>`, but here's a quick summary of the most often-used
  100. ones:
  101. :attr:`~Field.null`
  102. If ``True``, Django will store empty values as ``NULL`` in the database.
  103. Default is ``False``.
  104. :attr:`~Field.blank`
  105. If ``True``, the field is allowed to be blank. Default is ``False``.
  106. Note that this is different than :attr:`~Field.null`.
  107. :attr:`~Field.null` is purely database-related, whereas
  108. :attr:`~Field.blank` is validation-related. If a field has
  109. :attr:`blank=True <Field.blank>`, form validation will
  110. allow entry of an empty value. If a field has :attr:`blank=False
  111. <Field.blank>`, the field will be required.
  112. :attr:`~Field.choices`
  113. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
  114. this field. If this is given, the default form widget will be a select box
  115. instead of the standard text field and will limit choices to the choices
  116. given.
  117. A choices list looks like this::
  118. YEAR_IN_SCHOOL_CHOICES = (
  119. ('FR', 'Freshman'),
  120. ('SO', 'Sophomore'),
  121. ('JR', 'Junior'),
  122. ('SR', 'Senior'),
  123. ('GR', 'Graduate'),
  124. )
  125. The first element in each tuple is the value that will be stored in the
  126. database, the second element will be displayed by the default form widget
  127. or in a ModelChoiceField. Given an instance of a model object, the
  128. display value for a choices field can be accessed using the
  129. ``get_FOO_display`` method. For example::
  130. from django.db import models
  131. class Person(models.Model):
  132. SHIRT_SIZES = (
  133. ('S', 'Small'),
  134. ('M', 'Medium'),
  135. ('L', 'Large'),
  136. )
  137. name = models.CharField(max_length=60)
  138. shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
  139. ::
  140. >>> p = Person(name="Fred Flintstone", shirt_size="L")
  141. >>> p.save()
  142. >>> p.shirt_size
  143. 'L'
  144. >>> p.get_shirt_size_display()
  145. 'Large'
  146. :attr:`~Field.default`
  147. The default value for the field. This can be a value or a callable
  148. object. If callable it will be called every time a new object is
  149. created.
  150. :attr:`~Field.help_text`
  151. Extra "help" text to be displayed with the form widget. It's useful for
  152. documentation even if your field isn't used on a form.
  153. :attr:`~Field.primary_key`
  154. If ``True``, this field is the primary key for the model.
  155. If you don't specify :attr:`primary_key=True <Field.primary_key>` for
  156. any fields in your model, Django will automatically add an
  157. :class:`IntegerField` to hold the primary key, so you don't need to set
  158. :attr:`primary_key=True <Field.primary_key>` on any of your fields
  159. unless you want to override the default primary-key behavior. For more,
  160. see :ref:`automatic-primary-key-fields`.
  161. :attr:`~Field.unique`
  162. If ``True``, this field must be unique throughout the table.
  163. Again, these are just short descriptions of the most common field options. Full
  164. details can be found in the :ref:`common model field option reference
  165. <common-model-field-options>`.
  166. .. _automatic-primary-key-fields:
  167. Automatic primary key fields
  168. ----------------------------
  169. By default, Django gives each model the following field::
  170. id = models.AutoField(primary_key=True)
  171. This is an auto-incrementing primary key.
  172. If you'd like to specify a custom primary key, just specify
  173. :attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
  174. sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
  175. ``id`` column.
  176. Each model requires exactly one field to have :attr:`primary_key=True
  177. <Field.primary_key>` (either explicitly declared or automatically added).
  178. .. _verbose-field-names:
  179. Verbose field names
  180. -------------------
  181. Each field type, except for :class:`~django.db.models.ForeignKey`,
  182. :class:`~django.db.models.ManyToManyField` and
  183. :class:`~django.db.models.OneToOneField`, takes an optional first positional
  184. argument -- a verbose name. If the verbose name isn't given, Django will
  185. automatically create it using the field's attribute name, converting underscores
  186. to spaces.
  187. In this example, the verbose name is ``"person's first name"``::
  188. first_name = models.CharField("person's first name", max_length=30)
  189. In this example, the verbose name is ``"first name"``::
  190. first_name = models.CharField(max_length=30)
  191. :class:`~django.db.models.ForeignKey`,
  192. :class:`~django.db.models.ManyToManyField` and
  193. :class:`~django.db.models.OneToOneField` require the first argument to be a
  194. model class, so use the :attr:`~Field.verbose_name` keyword argument::
  195. poll = models.ForeignKey(Poll, verbose_name="the related poll")
  196. sites = models.ManyToManyField(Site, verbose_name="list of sites")
  197. place = models.OneToOneField(Place, verbose_name="related place")
  198. The convention is not to capitalize the first letter of the
  199. :attr:`~Field.verbose_name`. Django will automatically capitalize the first
  200. letter where it needs to.
  201. Relationships
  202. -------------
  203. Clearly, the power of relational databases lies in relating tables to each
  204. other. Django offers ways to define the three most common types of database
  205. relationships: many-to-one, many-to-many and one-to-one.
  206. Many-to-one relationships
  207. ~~~~~~~~~~~~~~~~~~~~~~~~~
  208. To define a many-to-one relationship, use :class:`django.db.models.ForeignKey`.
  209. You use it just like any other :class:`~django.db.models.Field` type: by
  210. including it as a class attribute of your model.
  211. :class:`~django.db.models.ForeignKey` requires a positional argument: the class
  212. to which the model is related.
  213. For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
  214. ``Manufacturer`` makes multiple cars but each ``Car`` only has one
  215. ``Manufacturer`` -- use the following definitions::
  216. from django.db import models
  217. class Manufacturer(models.Model):
  218. # ...
  219. pass
  220. class Car(models.Model):
  221. manufacturer = models.ForeignKey(Manufacturer)
  222. # ...
  223. You can also create :ref:`recursive relationships <recursive-relationships>` (an
  224. object with a many-to-one relationship to itself) and :ref:`relationships to
  225. models not yet defined <lazy-relationships>`; see :ref:`the model field
  226. reference <ref-foreignkey>` for details.
  227. It's suggested, but not required, that the name of a
  228. :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
  229. above) be the name of the model, lowercase. You can, of course, call the field
  230. whatever you want. For example::
  231. class Car(models.Model):
  232. company_that_makes_it = models.ForeignKey(Manufacturer)
  233. # ...
  234. .. seealso::
  235. :class:`~django.db.models.ForeignKey` fields accept a number of extra
  236. arguments which are explained in :ref:`the model field reference
  237. <foreign-key-arguments>`. These options help define how the relationship
  238. should work; all are optional.
  239. For details on accessing backwards-related objects, see the
  240. :ref:`Following relationships backward example <backwards-related-objects>`.
  241. For sample code, see the :doc:`Many-to-one relationship model example
  242. </topics/db/examples/many_to_one>`.
  243. Many-to-many relationships
  244. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  245. To define a many-to-many relationship, use
  246. :class:`~django.db.models.ManyToManyField`. You use it just like any other
  247. :class:`~django.db.models.Field` type: by including it as a class attribute of
  248. your model.
  249. :class:`~django.db.models.ManyToManyField` requires a positional argument: the
  250. class to which the model is related.
  251. For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
  252. ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
  253. -- here's how you'd represent that::
  254. from django.db import models
  255. class Topping(models.Model):
  256. # ...
  257. pass
  258. class Pizza(models.Model):
  259. # ...
  260. toppings = models.ManyToManyField(Topping)
  261. As with :class:`~django.db.models.ForeignKey`, you can also create
  262. :ref:`recursive relationships <recursive-relationships>` (an object with a
  263. many-to-many relationship to itself) and :ref:`relationships to models not yet
  264. defined <lazy-relationships>`; see :ref:`the model field reference
  265. <ref-manytomany>` for details.
  266. It's suggested, but not required, that the name of a
  267. :class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)
  268. be a plural describing the set of related model objects.
  269. It doesn't matter which model has the
  270. :class:`~django.db.models.ManyToManyField`, but you should only put it in one
  271. of the models -- not both.
  272. Generally, :class:`~django.db.models.ManyToManyField` instances should go in
  273. the object that's going to be edited on a form. In the above example,
  274. ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a ``pizzas``
  275. :class:`~django.db.models.ManyToManyField` ) because it's more natural to think
  276. about a pizza having toppings than a topping being on multiple pizzas. The way
  277. it's set up above, the ``Pizza`` form would let users select the toppings.
  278. .. seealso::
  279. See the :doc:`Many-to-many relationship model example
  280. </topics/db/examples/many_to_many>` for a full example.
  281. :class:`~django.db.models.ManyToManyField` fields also accept a number of
  282. extra arguments which are explained in :ref:`the model field reference
  283. <manytomany-arguments>`. These options help define how the relationship
  284. should work; all are optional.
  285. .. _intermediary-manytomany:
  286. Extra fields on many-to-many relationships
  287. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  288. When you're only dealing with simple many-to-many relationships such as
  289. mixing and matching pizzas and toppings, a standard
  290. :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes
  291. you may need to associate data with the relationship between two models.
  292. For example, consider the case of an application tracking the musical groups
  293. which musicians belong to. There is a many-to-many relationship between a person
  294. and the groups of which they are a member, so you could use a
  295. :class:`~django.db.models.ManyToManyField` to represent this relationship.
  296. However, there is a lot of detail about the membership that you might want to
  297. collect, such as the date at which the person joined the group.
  298. For these situations, Django allows you to specify the model that will be used
  299. to govern the many-to-many relationship. You can then put extra fields on the
  300. intermediate model. The intermediate model is associated with the
  301. :class:`~django.db.models.ManyToManyField` using the
  302. :attr:`through <ManyToManyField.through>` argument to point to the model
  303. that will act as an intermediary. For our musician example, the code would look
  304. something like this::
  305. from django.db import models
  306. class Person(models.Model):
  307. name = models.CharField(max_length=128)
  308. def __str__(self): # __unicode__ on Python 2
  309. return self.name
  310. class Group(models.Model):
  311. name = models.CharField(max_length=128)
  312. members = models.ManyToManyField(Person, through='Membership')
  313. def __str__(self): # __unicode__ on Python 2
  314. return self.name
  315. class Membership(models.Model):
  316. person = models.ForeignKey(Person)
  317. group = models.ForeignKey(Group)
  318. date_joined = models.DateField()
  319. invite_reason = models.CharField(max_length=64)
  320. When you set up the intermediary model, you explicitly specify foreign
  321. keys to the models that are involved in the many-to-many relationship. This
  322. explicit declaration defines how the two models are related.
  323. There are a few restrictions on the intermediate model:
  324. * Your intermediate model must contain one - and *only* one - foreign key
  325. to the source model (this would be ``Group`` in our example), or you must
  326. explicitly specify the foreign keys Django should use for the relationship
  327. using :attr:`ManyToManyField.through_fields <ManyToManyField.through_fields>`.
  328. If you have more than one foreign key and ``through_fields`` is not
  329. specified, a validation error will be raised. A similar restriction applies
  330. to the foreign key to the target model (this would be ``Person`` in our
  331. example).
  332. * For a model which has a many-to-many relationship to itself through an
  333. intermediary model, two foreign keys to the same model are permitted, but
  334. they will be treated as the two (different) sides of the many-to-many
  335. relationship. If there are *more* than two foreign keys though, you
  336. must also specify ``through_fields`` as above, or a validation error
  337. will be raised.
  338. * When defining a many-to-many relationship from a model to
  339. itself, using an intermediary model, you *must* use
  340. :attr:`symmetrical=False <ManyToManyField.symmetrical>` (see
  341. :ref:`the model field reference <manytomany-arguments>`).
  342. .. versionchanged:: 1.7
  343. In Django 1.6 and earlier, intermediate models containing more than one
  344. foreign key to any of the models involved in the many-to-many relationship
  345. used to be prohibited.
  346. Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
  347. your intermediary model (``Membership``, in this case), you're ready to start
  348. creating some many-to-many relationships. You do this by creating instances of
  349. the intermediate model::
  350. >>> ringo = Person.objects.create(name="Ringo Starr")
  351. >>> paul = Person.objects.create(name="Paul McCartney")
  352. >>> beatles = Group.objects.create(name="The Beatles")
  353. >>> m1 = Membership(person=ringo, group=beatles,
  354. ... date_joined=date(1962, 8, 16),
  355. ... invite_reason="Needed a new drummer.")
  356. >>> m1.save()
  357. >>> beatles.members.all()
  358. [<Person: Ringo Starr>]
  359. >>> ringo.group_set.all()
  360. [<Group: The Beatles>]
  361. >>> m2 = Membership.objects.create(person=paul, group=beatles,
  362. ... date_joined=date(1960, 8, 1),
  363. ... invite_reason="Wanted to form a band.")
  364. >>> beatles.members.all()
  365. [<Person: Ringo Starr>, <Person: Paul McCartney>]
  366. Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
  367. or assignment (i.e., ``beatles.members = [...]``) to create relationships::
  368. # THIS WILL NOT WORK
  369. >>> beatles.members.add(john)
  370. # NEITHER WILL THIS
  371. >>> beatles.members.create(name="George Harrison")
  372. # AND NEITHER WILL THIS
  373. >>> beatles.members = [john, paul, ringo, george]
  374. Why? You can't just create a relationship between a ``Person`` and a ``Group``
  375. - you need to specify all the detail for the relationship required by the
  376. ``Membership`` model. The simple ``add``, ``create`` and assignment calls
  377. don't provide a way to specify this extra detail. As a result, they are
  378. disabled for many-to-many relationships that use an intermediate model.
  379. The only way to create this type of relationship is to create instances of the
  380. intermediate model.
  381. The :meth:`~django.db.models.fields.related.RelatedManager.remove` method is
  382. disabled for similar reasons. However, the
  383. :meth:`~django.db.models.fields.related.RelatedManager.clear` method can be
  384. used to remove all many-to-many relationships for an instance::
  385. >>> # Beatles have broken up
  386. >>> beatles.members.clear()
  387. >>> # Note that this deletes the intermediate model instances
  388. >>> Membership.objects.all()
  389. []
  390. Once you have established the many-to-many relationships by creating instances
  391. of your intermediate model, you can issue queries. Just as with normal
  392. many-to-many relationships, you can query using the attributes of the
  393. many-to-many-related model::
  394. # Find all the groups with a member whose name starts with 'Paul'
  395. >>> Group.objects.filter(members__name__startswith='Paul')
  396. [<Group: The Beatles>]
  397. As you are using an intermediate model, you can also query on its attributes::
  398. # Find all the members of the Beatles that joined after 1 Jan 1961
  399. >>> Person.objects.filter(
  400. ... group__name='The Beatles',
  401. ... membership__date_joined__gt=date(1961,1,1))
  402. [<Person: Ringo Starr]
  403. If you need to access a membership's information you may do so by directly
  404. querying the ``Membership`` model::
  405. >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
  406. >>> ringos_membership.date_joined
  407. datetime.date(1962, 8, 16)
  408. >>> ringos_membership.invite_reason
  409. 'Needed a new drummer.'
  410. Another way to access the same information is by querying the
  411. :ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a
  412. ``Person`` object::
  413. >>> ringos_membership = ringo.membership_set.get(group=beatles)
  414. >>> ringos_membership.date_joined
  415. datetime.date(1962, 8, 16)
  416. >>> ringos_membership.invite_reason
  417. 'Needed a new drummer.'
  418. One-to-one relationships
  419. ~~~~~~~~~~~~~~~~~~~~~~~~
  420. To define a one-to-one relationship, use
  421. :class:`~django.db.models.OneToOneField`. You use it just like any other
  422. ``Field`` type: by including it as a class attribute of your model.
  423. This is most useful on the primary key of an object when that object "extends"
  424. another object in some way.
  425. :class:`~django.db.models.OneToOneField` requires a positional argument: the
  426. class to which the model is related.
  427. For example, if you were building a database of "places", you would
  428. build pretty standard stuff such as address, phone number, etc. in the
  429. database. Then, if you wanted to build a database of restaurants on
  430. top of the places, instead of repeating yourself and replicating those
  431. fields in the ``Restaurant`` model, you could make ``Restaurant`` have
  432. a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
  433. restaurant "is a" place; in fact, to handle this you'd typically use
  434. :ref:`inheritance <model-inheritance>`, which involves an implicit
  435. one-to-one relation).
  436. As with :class:`~django.db.models.ForeignKey`, a
  437. :ref:`recursive relationship <recursive-relationships>`
  438. can be defined and
  439. :ref:`references to as-yet undefined models <lazy-relationships>`
  440. can be made; see :ref:`the model field reference <ref-onetoone>` for details.
  441. .. seealso::
  442. See the :doc:`One-to-one relationship model example
  443. </topics/db/examples/one_to_one>` for a full example.
  444. :class:`~django.db.models.OneToOneField` fields also accept one specific,
  445. optional ``parent_link`` argument described in the :ref:`model field
  446. reference <ref-onetoone>`.
  447. :class:`~django.db.models.OneToOneField` classes used to automatically become
  448. the primary key on a model. This is no longer true (although you can manually
  449. pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
  450. Thus, it's now possible to have multiple fields of type
  451. :class:`~django.db.models.OneToOneField` on a single model.
  452. Models across files
  453. -------------------
  454. It's perfectly OK to relate a model to one from another app. To do this, import
  455. the related model at the top of the file where your model is defined. Then,
  456. just refer to the other model class wherever needed. For example::
  457. from django.db import models
  458. from geography.models import ZipCode
  459. class Restaurant(models.Model):
  460. # ...
  461. zip_code = models.ForeignKey(ZipCode)
  462. Field name restrictions
  463. -----------------------
  464. Django places only two restrictions on model field names:
  465. 1. A field name cannot be a Python reserved word, because that would result
  466. in a Python syntax error. For example::
  467. class Example(models.Model):
  468. pass = models.IntegerField() # 'pass' is a reserved word!
  469. 2. A field name cannot contain more than one underscore in a row, due to
  470. the way Django's query lookup syntax works. For example::
  471. class Example(models.Model):
  472. foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
  473. These limitations can be worked around, though, because your field name doesn't
  474. necessarily have to match your database column name. See the
  475. :attr:`~Field.db_column` option.
  476. SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
  477. model field names, because Django escapes all database table names and column
  478. names in every underlying SQL query. It uses the quoting syntax of your
  479. particular database engine.
  480. Custom field types
  481. ------------------
  482. If one of the existing model fields cannot be used to fit your purposes, or if
  483. you wish to take advantage of some less common database column types, you can
  484. create your own field class. Full coverage of creating your own fields is
  485. provided in :doc:`/howto/custom-model-fields`.
  486. .. _meta-options:
  487. Meta options
  488. ============
  489. Give your model metadata by using an inner ``class Meta``, like so::
  490. from django.db import models
  491. class Ox(models.Model):
  492. horn_length = models.IntegerField()
  493. class Meta:
  494. ordering = ["horn_length"]
  495. verbose_name_plural = "oxen"
  496. Model metadata is "anything that's not a field", such as ordering options
  497. (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
  498. human-readable singular and plural names (:attr:`~Options.verbose_name` and
  499. :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
  500. Meta`` to a model is completely optional.
  501. A complete list of all possible ``Meta`` options can be found in the :doc:`model
  502. option reference </ref/models/options>`.
  503. .. _model-attributes:
  504. Model attributes
  505. ================
  506. ``objects``
  507. The most important attribute of a model is the
  508. :class:`~django.db.models.Manager`. It's the interface through which
  509. database query operations are provided to Django models and is used to
  510. :ref:`retrieve the instances <retrieving-objects>` from the database. If no
  511. custom ``Manager`` is defined, the default name is ``objects``. Managers
  512. are only accessible via model classes, not the model instances.
  513. .. _model-methods:
  514. Model methods
  515. =============
  516. Define custom methods on a model to add custom "row-level" functionality to your
  517. objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
  518. "table-wide" things, model methods should act on a particular model instance.
  519. This is a valuable technique for keeping business logic in one place -- the
  520. model.
  521. For example, this model has a few custom methods::
  522. from django.db import models
  523. class Person(models.Model):
  524. first_name = models.CharField(max_length=50)
  525. last_name = models.CharField(max_length=50)
  526. birth_date = models.DateField()
  527. address = models.CharField(max_length=100)
  528. city = models.CharField(max_length=50)
  529. state = models.CharField(max_length=2) # yes, this is America-centric
  530. def baby_boomer_status(self):
  531. "Returns the person's baby-boomer status."
  532. import datetime
  533. if self.birth_date < datetime.date(1945, 8, 1):
  534. return "Pre-boomer"
  535. elif self.birth_date < datetime.date(1965, 1, 1):
  536. return "Baby boomer"
  537. else:
  538. return "Post-boomer"
  539. def is_midwestern(self):
  540. "Returns True if this person is from the Midwest."
  541. return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
  542. def _get_full_name(self):
  543. "Returns the person's full name."
  544. return '%s %s' % (self.first_name, self.last_name)
  545. full_name = property(_get_full_name)
  546. The last method in this example is a :term:`property`.
  547. The :doc:`model instance reference </ref/models/instances>` has a complete list
  548. of :ref:`methods automatically given to each model <model-instance-methods>`.
  549. You can override most of these -- see `overriding predefined model methods`_,
  550. below -- but there are a couple that you'll almost always want to define:
  551. :meth:`~Model.__str__` (Python 3)
  552. Python 3 equivalent of ``__unicode__()``.
  553. :meth:`~Model.__unicode__` (Python 2)
  554. A Python "magic method" that returns a unicode "representation" of any
  555. object. This is what Python and Django will use whenever a model
  556. instance needs to be coerced and displayed as a plain string. Most
  557. notably, this happens when you display an object in an interactive
  558. console or in the admin.
  559. You'll always want to define this method; the default isn't very helpful
  560. at all.
  561. :meth:`~Model.get_absolute_url`
  562. This tells Django how to calculate the URL for an object. Django uses
  563. this in its admin interface, and any time it needs to figure out a URL
  564. for an object.
  565. Any object that has a URL that uniquely identifies it should define this
  566. method.
  567. .. _overriding-model-methods:
  568. Overriding predefined model methods
  569. -----------------------------------
  570. There's another set of :ref:`model methods <model-instance-methods>` that
  571. encapsulate a bunch of database behavior that you'll want to customize. In
  572. particular you'll often want to change the way :meth:`~Model.save` and
  573. :meth:`~Model.delete` work.
  574. You're free to override these methods (and any other model method) to alter
  575. behavior.
  576. A classic use-case for overriding the built-in methods is if you want something
  577. to happen whenever you save an object. For example (see
  578. :meth:`~Model.save` for documentation of the parameters it accepts)::
  579. from django.db import models
  580. class Blog(models.Model):
  581. name = models.CharField(max_length=100)
  582. tagline = models.TextField()
  583. def save(self, *args, **kwargs):
  584. do_something()
  585. super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
  586. do_something_else()
  587. You can also prevent saving::
  588. from django.db import models
  589. class Blog(models.Model):
  590. name = models.CharField(max_length=100)
  591. tagline = models.TextField()
  592. def save(self, *args, **kwargs):
  593. if self.name == "Yoko Ono's blog":
  594. return # Yoko shall never have her own blog!
  595. else:
  596. super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
  597. It's important to remember to call the superclass method -- that's
  598. that ``super(Blog, self).save(*args, **kwargs)`` business -- to ensure
  599. that the object still gets saved into the database. If you forget to
  600. call the superclass method, the default behavior won't happen and the
  601. database won't get touched.
  602. It's also important that you pass through the arguments that can be
  603. passed to the model method -- that's what the ``*args, **kwargs`` bit
  604. does. Django will, from time to time, extend the capabilities of
  605. built-in model methods, adding new arguments. If you use ``*args,
  606. **kwargs`` in your method definitions, you are guaranteed that your
  607. code will automatically support those arguments when they are added.
  608. .. admonition:: Overridden model methods are not called on bulk operations
  609. Note that the :meth:`~Model.delete()` method for an object is not
  610. necessarily called when :ref:`deleting objects in bulk using a
  611. QuerySet<topics-db-queries-delete>`. To ensure customized delete logic
  612. gets executed, you can use :data:`~django.db.models.signals.pre_delete`
  613. and/or :data:`~django.db.models.signals.post_delete` signals.
  614. Unfortunately, there isn't a workaround when
  615. :meth:`creating<django.db.models.query.QuerySet.bulk_create>` or
  616. :meth:`updating<django.db.models.query.QuerySet.update>` objects in bulk,
  617. since none of :meth:`~Model.save()`,
  618. :data:`~django.db.models.signals.pre_save`, and
  619. :data:`~django.db.models.signals.post_save` are called.
  620. Executing custom SQL
  621. --------------------
  622. Another common pattern is writing custom SQL statements in model methods and
  623. module-level methods. For more details on using raw SQL, see the documentation
  624. on :doc:`using raw SQL</topics/db/sql>`.
  625. .. _model-inheritance:
  626. Model inheritance
  627. =================
  628. Model inheritance in Django works almost identically to the way normal
  629. class inheritance works in Python. The only decision you have to make
  630. is whether you want the parent models to be models in their own right
  631. (with their own database tables), or if the parents are just holders
  632. of common information that will only be visible through the child
  633. models.
  634. There are three styles of inheritance that are possible in Django.
  635. 1. Often, you will just want to use the parent class to hold information that
  636. you don't want to have to type out for each child model. This class isn't
  637. going to ever be used in isolation, so :ref:`abstract-base-classes` are
  638. what you're after.
  639. 2. If you're subclassing an existing model (perhaps something from another
  640. application entirely) and want each model to have its own database table,
  641. :ref:`multi-table-inheritance` is the way to go.
  642. 3. Finally, if you only want to modify the Python-level behavior of a model,
  643. without changing the models fields in any way, you can use
  644. :ref:`proxy-models`.
  645. .. _abstract-base-classes:
  646. Abstract base classes
  647. ---------------------
  648. Abstract base classes are useful when you want to put some common
  649. information into a number of other models. You write your base class
  650. and put ``abstract=True`` in the :ref:`Meta <meta-options>`
  651. class. This model will then not be used to create any database
  652. table. Instead, when it is used as a base class for other models, its
  653. fields will be added to those of the child class. It is an error to
  654. have fields in the abstract base class with the same name as those in
  655. the child (and Django will raise an exception).
  656. An example::
  657. from django.db import models
  658. class CommonInfo(models.Model):
  659. name = models.CharField(max_length=100)
  660. age = models.PositiveIntegerField()
  661. class Meta:
  662. abstract = True
  663. class Student(CommonInfo):
  664. home_group = models.CharField(max_length=5)
  665. The ``Student`` model will have three fields: ``name``, ``age`` and
  666. ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
  667. model, since it is an abstract base class. It does not generate a database
  668. table or have a manager, and cannot be instantiated or saved directly.
  669. For many uses, this type of model inheritance will be exactly what you want.
  670. It provides a way to factor out common information at the Python level, whilst
  671. still only creating one database table per child model at the database level.
  672. ``Meta`` inheritance
  673. ~~~~~~~~~~~~~~~~~~~~
  674. When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
  675. inner class you declared in the base class available as an
  676. attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
  677. class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
  678. extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
  679. from django.db import models
  680. class CommonInfo(models.Model):
  681. # ...
  682. class Meta:
  683. abstract = True
  684. ordering = ['name']
  685. class Student(CommonInfo):
  686. # ...
  687. class Meta(CommonInfo.Meta):
  688. db_table = 'student_info'
  689. Django does make one adjustment to the :ref:`Meta <meta-options>` class of an abstract base
  690. class: before installing the :ref:`Meta <meta-options>` attribute, it sets ``abstract=False``.
  691. This means that children of abstract base classes don't automatically become
  692. abstract classes themselves. Of course, you can make an abstract base class
  693. that inherits from another abstract base class. You just need to remember to
  694. explicitly set ``abstract=True`` each time.
  695. Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
  696. abstract base class. For example, including ``db_table`` would mean that all
  697. the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
  698. the same database table, which is almost certainly not what you want.
  699. .. _abstract-related-name:
  700. Be careful with ``related_name``
  701. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  702. If you are using the :attr:`~django.db.models.ForeignKey.related_name` attribute on a ``ForeignKey`` or
  703. ``ManyToManyField``, you must always specify a *unique* reverse name for the
  704. field. This would normally cause a problem in abstract base classes, since the
  705. fields on this class are included into each of the child classes, with exactly
  706. the same values for the attributes (including :attr:`~django.db.models.ForeignKey.related_name`) each time.
  707. To work around this problem, when you are using :attr:`~django.db.models.ForeignKey.related_name` in an
  708. abstract base class (only), part of the name should contain
  709. ``'%(app_label)s'`` and ``'%(class)s'``.
  710. - ``'%(class)s'`` is replaced by the lower-cased name of the child class
  711. that the field is used in.
  712. - ``'%(app_label)s'`` is replaced by the lower-cased name of the app the child
  713. class is contained within. Each installed application name must be unique
  714. and the model class names within each app must also be unique, therefore the
  715. resulting name will end up being different.
  716. For example, given an app ``common/models.py``::
  717. from django.db import models
  718. class Base(models.Model):
  719. m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
  720. class Meta:
  721. abstract = True
  722. class ChildA(Base):
  723. pass
  724. class ChildB(Base):
  725. pass
  726. Along with another app ``rare/models.py``::
  727. from common.models import Base
  728. class ChildB(Base):
  729. pass
  730. The reverse name of the ``common.ChildA.m2m`` field will be
  731. ``common_childa_related``, whilst the reverse name of the
  732. ``common.ChildB.m2m`` field will be ``common_childb_related``, and finally the
  733. reverse name of the ``rare.ChildB.m2m`` field will be ``rare_childb_related``.
  734. It is up to you how you use the ``'%(class)s'`` and ``'%(app_label)s`` portion
  735. to construct your related name, but if you forget to use it, Django will raise
  736. errors when you perform system checks (or run :djadmin:`migrate`).
  737. If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
  738. attribute for a field in an abstract base class, the default reverse name will
  739. be the name of the child class followed by ``'_set'``, just as it normally
  740. would be if you'd declared the field directly on the child class. For example,
  741. in the above code, if the :attr:`~django.db.models.ForeignKey.related_name`
  742. attribute was omitted, the reverse name for the ``m2m`` field would be
  743. ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``
  744. field.
  745. .. _multi-table-inheritance:
  746. Multi-table inheritance
  747. -----------------------
  748. The second type of model inheritance supported by Django is when each model in
  749. the hierarchy is a model all by itself. Each model corresponds to its own
  750. database table and can be queried and created individually. The inheritance
  751. relationship introduces links between the child model and each of its parents
  752. (via an automatically-created :class:`~django.db.models.OneToOneField`).
  753. For example::
  754. from django.db import models
  755. class Place(models.Model):
  756. name = models.CharField(max_length=50)
  757. address = models.CharField(max_length=80)
  758. class Restaurant(Place):
  759. serves_hot_dogs = models.BooleanField()
  760. serves_pizza = models.BooleanField()
  761. All of the fields of ``Place`` will also be available in ``Restaurant``,
  762. although the data will reside in a different database table. So these are both
  763. possible::
  764. >>> Place.objects.filter(name="Bob's Cafe")
  765. >>> Restaurant.objects.filter(name="Bob's Cafe")
  766. If you have a ``Place`` that is also a ``Restaurant``, you can get from the
  767. ``Place`` object to the ``Restaurant`` object by using the lower-case version
  768. of the model name::
  769. >>> p = Place.objects.get(id=12)
  770. # If p is a Restaurant object, this will give the child class:
  771. >>> p.restaurant
  772. <Restaurant: ...>
  773. However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
  774. created directly as a ``Place`` object or was the parent of some other class),
  775. referring to ``p.restaurant`` would raise a ``Restaurant.DoesNotExist``
  776. exception.
  777. ``Meta`` and multi-table inheritance
  778. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  779. In the multi-table inheritance situation, it doesn't make sense for a child
  780. class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
  781. have already been applied to the parent class and applying them again would
  782. normally only lead to contradictory behavior (this is in contrast with the
  783. abstract base class case, where the base class doesn't exist in its own
  784. right).
  785. So a child model does not have access to its parent's :ref:`Meta
  786. <meta-options>` class. However, there are a few limited cases where the child
  787. inherits behavior from the parent: if the child does not specify an
  788. :attr:`~django.db.models.Options.ordering` attribute or a
  789. :attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit
  790. these from its parent.
  791. If the parent has an ordering and you don't want the child to have any natural
  792. ordering, you can explicitly disable it::
  793. class ChildModel(ParentModel):
  794. # ...
  795. class Meta:
  796. # Remove parent's ordering effect
  797. ordering = []
  798. Inheritance and reverse relations
  799. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  800. Because multi-table inheritance uses an implicit
  801. :class:`~django.db.models.OneToOneField` to link the child and
  802. the parent, it's possible to move from the parent down to the child,
  803. as in the above example. However, this uses up the name that is the
  804. default :attr:`~django.db.models.ForeignKey.related_name` value for
  805. :class:`~django.db.models.ForeignKey` and
  806. :class:`~django.db.models.ManyToManyField` relations. If you
  807. are putting those types of relations on a subclass of another model,
  808. you **must** specify the
  809. :attr:`~django.db.models.ForeignKey.related_name` attribute on each
  810. such field. If you forget, Django will raise an error when you run
  811. :djadmin:`check` or :djadmin:`migrate`.
  812. For example, using the above ``Place`` class again, let's create another
  813. subclass with a :class:`~django.db.models.ManyToManyField`::
  814. class Supplier(Place):
  815. # Must specify related_name on all relations.
  816. customers = models.ManyToManyField(Restaurant, related_name='provider')
  817. Specifying the parent link field
  818. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  819. As mentioned, Django will automatically create a
  820. :class:`~django.db.models.OneToOneField` linking your child
  821. class back any non-abstract parent models. If you want to control the
  822. name of the attribute linking back to the parent, you can create your
  823. own :class:`~django.db.models.OneToOneField` and set
  824. :attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`
  825. to indicate that your field is the link back to the parent class.
  826. .. _proxy-models:
  827. Proxy models
  828. ------------
  829. When using :ref:`multi-table inheritance <multi-table-inheritance>`, a new
  830. database table is created for each subclass of a model. This is usually the
  831. desired behavior, since the subclass needs a place to store any additional
  832. data fields that are not present on the base class. Sometimes, however, you
  833. only want to change the Python behavior of a model -- perhaps to change the
  834. default manager, or add a new method.
  835. This is what proxy model inheritance is for: creating a *proxy* for the
  836. original model. You can create, delete and update instances of the proxy model
  837. and all the data will be saved as if you were using the original (non-proxied)
  838. model. The difference is that you can change things like the default model
  839. ordering or the default manager in the proxy, without having to alter the
  840. original.
  841. Proxy models are declared like normal models. You tell Django that it's a
  842. proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
  843. the ``Meta`` class to ``True``.
  844. For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
  845. from django.db import models
  846. class Person(models.Model):
  847. first_name = models.CharField(max_length=30)
  848. last_name = models.CharField(max_length=30)
  849. class MyPerson(Person):
  850. class Meta:
  851. proxy = True
  852. def do_something(self):
  853. # ...
  854. pass
  855. The ``MyPerson`` class operates on the same database table as its parent
  856. ``Person`` class. In particular, any new instances of ``Person`` will also be
  857. accessible through ``MyPerson``, and vice-versa::
  858. >>> p = Person.objects.create(first_name="foobar")
  859. >>> MyPerson.objects.get(first_name="foobar")
  860. <MyPerson: foobar>
  861. You could also use a proxy model to define a different default ordering on
  862. a model. You might not always want to order the ``Person`` model, but regularly
  863. order by the ``last_name`` attribute when you use the proxy. This is easy::
  864. class OrderedPerson(Person):
  865. class Meta:
  866. ordering = ["last_name"]
  867. proxy = True
  868. Now normal ``Person`` queries will be unordered
  869. and ``OrderedPerson`` queries will be ordered by ``last_name``.
  870. QuerySets still return the model that was requested
  871. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  872. There is no way to have Django return, say, a ``MyPerson`` object whenever you
  873. query for ``Person`` objects. A queryset for ``Person`` objects will return
  874. those types of objects. The whole point of proxy objects is that code relying
  875. on the original ``Person`` will use those and your own code can use the
  876. extensions you included (that no other code is relying on anyway). It is not
  877. a way to replace the ``Person`` (or any other) model everywhere with something
  878. of your own creation.
  879. Base class restrictions
  880. ~~~~~~~~~~~~~~~~~~~~~~~
  881. A proxy model must inherit from exactly one non-abstract model class. You
  882. can't inherit from multiple non-abstract models as the proxy model doesn't
  883. provide any connection between the rows in the different database tables. A
  884. proxy model can inherit from any number of abstract model classes, providing
  885. they do *not* define any model fields.
  886. Proxy models inherit any ``Meta`` options that they don't define from their
  887. non-abstract model parent (the model they are proxying for).
  888. Proxy model managers
  889. ~~~~~~~~~~~~~~~~~~~~
  890. If you don't specify any model managers on a proxy model, it inherits the
  891. managers from its model parents. If you define a manager on the proxy model,
  892. it will become the default, although any managers defined on the parent
  893. classes will still be available.
  894. Continuing our example from above, you could change the default manager used
  895. when you query the ``Person`` model like this::
  896. from django.db import models
  897. class NewManager(models.Manager):
  898. # ...
  899. pass
  900. class MyPerson(Person):
  901. objects = NewManager()
  902. class Meta:
  903. proxy = True
  904. If you wanted to add a new manager to the Proxy, without replacing the
  905. existing default, you can use the techniques described in the :ref:`custom
  906. manager <custom-managers-and-inheritance>` documentation: create a base class
  907. containing the new managers and inherit that after the primary base class::
  908. # Create an abstract class for the new manager.
  909. class ExtraManagers(models.Model):
  910. secondary = NewManager()
  911. class Meta:
  912. abstract = True
  913. class MyPerson(Person, ExtraManagers):
  914. class Meta:
  915. proxy = True
  916. You probably won't need to do this very often, but, when you do, it's
  917. possible.
  918. .. _proxy-vs-unmanaged-models:
  919. Differences between proxy inheritance and unmanaged models
  920. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  921. Proxy model inheritance might look fairly similar to creating an unmanaged
  922. model, using the :attr:`~django.db.models.Options.managed` attribute on a
  923. model's ``Meta`` class. The two alternatives are not quite the same and it's
  924. worth considering which one you should use.
  925. One difference is that you can (and, in fact, must unless you want an empty
  926. model) specify model fields on models with ``Meta.managed=False``. You could,
  927. with careful setting of :attr:`Meta.db_table
  928. <django.db.models.Options.db_table>` create an unmanaged model that shadowed
  929. an existing model and add Python methods to it. However, that would be very
  930. repetitive and fragile as you need to keep both copies synchronized if you
  931. make any changes.
  932. The other difference that is more important for proxy models, is how model
  933. managers are handled. Proxy models are intended to behave exactly like the
  934. model they are proxying for. So they inherit the parent model's managers,
  935. including the default manager. In the normal multi-table model inheritance
  936. case, children do not inherit managers from their parents as the custom
  937. managers aren't always appropriate when extra fields are involved. The
  938. :ref:`manager documentation <custom-managers-and-inheritance>` has more
  939. details about this latter case.
  940. When these two features were implemented, attempts were made to squash them
  941. into a single option. It turned out that interactions with inheritance, in
  942. general, and managers, in particular, made the API very complicated and
  943. potentially difficult to understand and use. It turned out that two options
  944. were needed in any case, so the current separation arose.
  945. So, the general rules are:
  946. 1. If you are mirroring an existing model or database table and don't want
  947. all the original database table columns, use ``Meta.managed=False``.
  948. That option is normally useful for modeling database views and tables
  949. not under the control of Django.
  950. 2. If you are wanting to change the Python-only behavior of a model, but
  951. keep all the same fields as in the original, use ``Meta.proxy=True``.
  952. This sets things up so that the proxy model is an exact copy of the
  953. storage structure of the original model when data is saved.
  954. .. _model-multiple-inheritance-topic:
  955. Multiple inheritance
  956. --------------------
  957. Just as with Python's subclassing, it's possible for a Django model to inherit
  958. from multiple parent models. Keep in mind that normal Python name resolution
  959. rules apply. The first base class that a particular name (e.g. :ref:`Meta
  960. <meta-options>`) appears in will be the one that is used; for example, this
  961. means that if multiple parents contain a :ref:`Meta <meta-options>` class,
  962. only the first one is going to be used, and all others will be ignored.
  963. Generally, you won't need to inherit from multiple parents. The main use-case
  964. where this is useful is for "mix-in" classes: adding a particular extra
  965. field or method to every class that inherits the mix-in. Try to keep your
  966. inheritance hierarchies as simple and straightforward as possible so that you
  967. won't have to struggle to work out where a particular piece of information is
  968. coming from.
  969. .. versionchanged:: 1.7
  970. Before Django 1.7, inheriting from multiple models that had an ``id`` primary
  971. key field did not raise an error, but could result in data loss. For example,
  972. consider these models (which no longer validate due to the clashing ``id``
  973. fields)::
  974. class Article(models.Model):
  975. headline = models.CharField(max_length=50)
  976. body = models.TextField()
  977. class Book(models.Model):
  978. title = models.CharField(max_length=50)
  979. class BookReview(Book, Article):
  980. pass
  981. This snippet demonstrates how creating a child object overwrote the value of a
  982. previously created parent object::
  983. >>> article = Article.objects.create(headline='Some piece of news.')
  984. >>> review = BookReview.objects.create(
  985. ... headline='Review of Little Red Riding Hood.',
  986. ... title='Little Red Riding Hood')
  987. >>>
  988. >>> assert Article.objects.get(pk=article.pk).headline == article.headline
  989. Traceback (most recent call last):
  990. File "<console>", line 1, in <module>
  991. AssertionError
  992. >>> # the "Some piece of news." headline has been overwritten.
  993. >>> Article.objects.get(pk=article.pk).headline
  994. 'Review of Little Red Riding Hood.'
  995. To properly use multiple inheritance, you can use an explicit
  996. :class:`~django.db.models.AutoField` in the base models::
  997. class Article(models.Model):
  998. article_id = models.AutoField(primary_key=True)
  999. ...
  1000. class Book(models.Model):
  1001. book_id = models.AutoField(primary_key=True)
  1002. ...
  1003. class BookReview(Book, Article):
  1004. pass
  1005. Or use a common ancestor to hold the :class:`~django.db.models.AutoField`::
  1006. class Piece(models.Model):
  1007. pass
  1008. class Article(Piece):
  1009. ...
  1010. class Book(Piece):
  1011. ...
  1012. class BookReview(Book, Article):
  1013. pass
  1014. Field name "hiding" is not permitted
  1015. -------------------------------------
  1016. In normal Python class inheritance, it is permissible for a child class to
  1017. override any attribute from the parent class. In Django, this is not permitted
  1018. for attributes that are :class:`~django.db.models.Field` instances (at
  1019. least, not at the moment). If a base class has a field called ``author``, you
  1020. cannot create another model field called ``author`` in any class that inherits
  1021. from that base class.
  1022. Overriding fields in a parent model leads to difficulties in areas such as
  1023. initializing new instances (specifying which field is being initialized in
  1024. ``Model.__init__``) and serialization. These are features which normal Python
  1025. class inheritance doesn't have to deal with in quite the same way, so the
  1026. difference between Django model inheritance and Python class inheritance isn't
  1027. arbitrary.
  1028. This restriction only applies to attributes which are
  1029. :class:`~django.db.models.Field` instances. Normal Python attributes
  1030. can be overridden if you wish. It also only applies to the name of the
  1031. attribute as Python sees it: if you are manually specifying the database
  1032. column name, you can have the same column name appearing in both a child and
  1033. an ancestor model for multi-table inheritance (they are columns in two
  1034. different database tables).
  1035. Django will raise a :exc:`~django.core.exceptions.FieldError` if you override
  1036. any model field in any ancestor model.