models.txt 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. u'L'
  144. >>> p.get_shirt_size_display()
  145. u'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. # On Python 3: def __str__(self):
  309. def __unicode__(self):
  310. return self.name
  311. class Group(models.Model):
  312. name = models.CharField(max_length=128)
  313. members = models.ManyToManyField(Person, through='Membership')
  314. # On Python 3: def __str__(self):
  315. def __unicode__(self):
  316. return self.name
  317. class Membership(models.Model):
  318. person = models.ForeignKey(Person)
  319. group = models.ForeignKey(Group)
  320. date_joined = models.DateField()
  321. invite_reason = models.CharField(max_length=64)
  322. When you set up the intermediary model, you explicitly specify foreign
  323. keys to the models that are involved in the ManyToMany relation. This
  324. explicit declaration defines how the two models are related.
  325. There are a few restrictions on the intermediate model:
  326. * Your intermediate model must contain one - and *only* one - foreign key
  327. to the target model (this would be ``Person`` in our example). If you
  328. have more than one foreign key, a validation error will be raised.
  329. * Your intermediate model must contain one - and *only* one - foreign key
  330. to the source model (this would be ``Group`` in our example). If you
  331. have more than one foreign key, a validation error will be raised.
  332. * The only exception to this is a model which has a many-to-many
  333. relationship to itself, through an intermediary model. In this
  334. case, two foreign keys to the same model are permitted, but they
  335. will be treated as the two (different) sides of the many-to-many
  336. relation.
  337. * When defining a many-to-many relationship from a model to
  338. itself, using an intermediary model, you *must* use
  339. :attr:`symmetrical=False <ManyToManyField.symmetrical>` (see
  340. :ref:`the model field reference <manytomany-arguments>`).
  341. Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
  342. your intermediary model (``Membership``, in this case), you're ready to start
  343. creating some many-to-many relationships. You do this by creating instances of
  344. the intermediate model::
  345. >>> ringo = Person.objects.create(name="Ringo Starr")
  346. >>> paul = Person.objects.create(name="Paul McCartney")
  347. >>> beatles = Group.objects.create(name="The Beatles")
  348. >>> m1 = Membership(person=ringo, group=beatles,
  349. ... date_joined=date(1962, 8, 16),
  350. ... invite_reason= "Needed a new drummer.")
  351. >>> m1.save()
  352. >>> beatles.members.all()
  353. [<Person: Ringo Starr>]
  354. >>> ringo.group_set.all()
  355. [<Group: The Beatles>]
  356. >>> m2 = Membership.objects.create(person=paul, group=beatles,
  357. ... date_joined=date(1960, 8, 1),
  358. ... invite_reason= "Wanted to form a band.")
  359. >>> beatles.members.all()
  360. [<Person: Ringo Starr>, <Person: Paul McCartney>]
  361. Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
  362. or assignment (i.e., ``beatles.members = [...]``) to create relationships::
  363. # THIS WILL NOT WORK
  364. >>> beatles.members.add(john)
  365. # NEITHER WILL THIS
  366. >>> beatles.members.create(name="George Harrison")
  367. # AND NEITHER WILL THIS
  368. >>> beatles.members = [john, paul, ringo, george]
  369. Why? You can't just create a relationship between a ``Person`` and a ``Group``
  370. - you need to specify all the detail for the relationship required by the
  371. ``Membership`` model. The simple ``add``, ``create`` and assignment calls
  372. don't provide a way to specify this extra detail. As a result, they are
  373. disabled for many-to-many relationships that use an intermediate model.
  374. The only way to create this type of relationship is to create instances of the
  375. intermediate model.
  376. The :meth:`~django.db.models.fields.related.RelatedManager.remove` method is
  377. disabled for similar reasons. However, the
  378. :meth:`~django.db.models.fields.related.RelatedManager.clear` method can be
  379. used to remove all many-to-many relationships for an instance::
  380. # Beatles have broken up
  381. >>> beatles.members.clear()
  382. Once you have established the many-to-many relationships by creating instances
  383. of your intermediate model, you can issue queries. Just as with normal
  384. many-to-many relationships, you can query using the attributes of the
  385. many-to-many-related model::
  386. # Find all the groups with a member whose name starts with 'Paul'
  387. >>> Group.objects.filter(members__name__startswith='Paul')
  388. [<Group: The Beatles>]
  389. As you are using an intermediate model, you can also query on its attributes::
  390. # Find all the members of the Beatles that joined after 1 Jan 1961
  391. >>> Person.objects.filter(
  392. ... group__name='The Beatles',
  393. ... membership__date_joined__gt=date(1961,1,1))
  394. [<Person: Ringo Starr]
  395. If you need to access a membership's information you may do so by directly
  396. querying the ``Membership`` model::
  397. >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
  398. >>> ringos_membership.date_joined
  399. datetime.date(1962, 8, 16)
  400. >>> ringos_membership.invite_reason
  401. u'Needed a new drummer.'
  402. Another way to access the same information is by querying the
  403. :ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a
  404. ``Person`` object::
  405. >>> ringos_membership = ringo.membership_set.get(group=beatles)
  406. >>> ringos_membership.date_joined
  407. datetime.date(1962, 8, 16)
  408. >>> ringos_membership.invite_reason
  409. u'Needed a new drummer.'
  410. One-to-one relationships
  411. ~~~~~~~~~~~~~~~~~~~~~~~~
  412. To define a one-to-one relationship, use
  413. :class:`~django.db.models.OneToOneField`. You use it just like any other
  414. ``Field`` type: by including it as a class attribute of your model.
  415. This is most useful on the primary key of an object when that object "extends"
  416. another object in some way.
  417. :class:`~django.db.models.OneToOneField` requires a positional argument: the
  418. class to which the model is related.
  419. For example, if you were building a database of "places", you would
  420. build pretty standard stuff such as address, phone number, etc. in the
  421. database. Then, if you wanted to build a database of restaurants on
  422. top of the places, instead of repeating yourself and replicating those
  423. fields in the ``Restaurant`` model, you could make ``Restaurant`` have
  424. a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
  425. restaurant "is a" place; in fact, to handle this you'd typically use
  426. :ref:`inheritance <model-inheritance>`, which involves an implicit
  427. one-to-one relation).
  428. As with :class:`~django.db.models.ForeignKey`, a
  429. :ref:`recursive relationship <recursive-relationships>`
  430. can be defined and
  431. :ref:`references to as-yet undefined models <lazy-relationships>`
  432. can be made; see :ref:`the model field reference <ref-onetoone>` for details.
  433. .. seealso::
  434. See the :doc:`One-to-one relationship model example
  435. </topics/db/examples/one_to_one>` for a full example.
  436. :class:`~django.db.models.OneToOneField` fields also accept one specific,
  437. optional ``parent_link`` argument described in the :ref:`model field
  438. reference <ref-onetoone>`.
  439. :class:`~django.db.models.OneToOneField` classes used to automatically become
  440. the primary key on a model. This is no longer true (although you can manually
  441. pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
  442. Thus, it's now possible to have multiple fields of type
  443. :class:`~django.db.models.OneToOneField` on a single model.
  444. Models across files
  445. -------------------
  446. It's perfectly OK to relate a model to one from another app. To do this, import
  447. the related model at the top of the file where your model is defined. Then,
  448. just refer to the other model class wherever needed. For example::
  449. from django.db import models
  450. from geography.models import ZipCode
  451. class Restaurant(models.Model):
  452. # ...
  453. zip_code = models.ForeignKey(ZipCode)
  454. Field name restrictions
  455. -----------------------
  456. Django places only two restrictions on model field names:
  457. 1. A field name cannot be a Python reserved word, because that would result
  458. in a Python syntax error. For example::
  459. class Example(models.Model):
  460. pass = models.IntegerField() # 'pass' is a reserved word!
  461. 2. A field name cannot contain more than one underscore in a row, due to
  462. the way Django's query lookup syntax works. For example::
  463. class Example(models.Model):
  464. foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
  465. These limitations can be worked around, though, because your field name doesn't
  466. necessarily have to match your database column name. See the
  467. :attr:`~Field.db_column` option.
  468. SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
  469. model field names, because Django escapes all database table names and column
  470. names in every underlying SQL query. It uses the quoting syntax of your
  471. particular database engine.
  472. Custom field types
  473. ------------------
  474. If one of the existing model fields cannot be used to fit your purposes, or if
  475. you wish to take advantage of some less common database column types, you can
  476. create your own field class. Full coverage of creating your own fields is
  477. provided in :doc:`/howto/custom-model-fields`.
  478. .. _meta-options:
  479. Meta options
  480. ============
  481. Give your model metadata by using an inner ``class Meta``, like so::
  482. from django.db import models
  483. class Ox(models.Model):
  484. horn_length = models.IntegerField()
  485. class Meta:
  486. ordering = ["horn_length"]
  487. verbose_name_plural = "oxen"
  488. Model metadata is "anything that's not a field", such as ordering options
  489. (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
  490. human-readable singular and plural names (:attr:`~Options.verbose_name` and
  491. :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
  492. Meta`` to a model is completely optional.
  493. A complete list of all possible ``Meta`` options can be found in the :doc:`model
  494. option reference </ref/models/options>`.
  495. .. _model-methods:
  496. Model methods
  497. =============
  498. Define custom methods on a model to add custom "row-level" functionality to your
  499. objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
  500. "table-wide" things, model methods should act on a particular model instance.
  501. This is a valuable technique for keeping business logic in one place -- the
  502. model.
  503. For example, this model has a few custom methods::
  504. from django.db import models
  505. class Person(models.Model):
  506. first_name = models.CharField(max_length=50)
  507. last_name = models.CharField(max_length=50)
  508. birth_date = models.DateField()
  509. address = models.CharField(max_length=100)
  510. city = models.CharField(max_length=50)
  511. state = models.CharField(max_length=2) # yes, this is America-centric
  512. def baby_boomer_status(self):
  513. "Returns the person's baby-boomer status."
  514. import datetime
  515. if self.birth_date < datetime.date(1945, 8, 1):
  516. return "Pre-boomer"
  517. elif self.birth_date < datetime.date(1965, 1, 1):
  518. return "Baby boomer"
  519. else:
  520. return "Post-boomer"
  521. def is_midwestern(self):
  522. "Returns True if this person is from the Midwest."
  523. return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
  524. def _get_full_name(self):
  525. "Returns the person's full name."
  526. return '%s %s' % (self.first_name, self.last_name)
  527. full_name = property(_get_full_name)
  528. The last method in this example is a :term:`property`.
  529. The :doc:`model instance reference </ref/models/instances>` has a complete list
  530. of :ref:`methods automatically given to each model <model-instance-methods>`.
  531. You can override most of these -- see `overriding predefined model methods`_,
  532. below -- but there are a couple that you'll almost always want to define:
  533. :meth:`~Model.__str__` (Python 3)
  534. Python 3 equivalent of ``__unicode__()``.
  535. :meth:`~Model.__unicode__` (Python 2)
  536. A Python "magic method" that returns a unicode "representation" of any
  537. object. This is what Python and Django will use whenever a model
  538. instance needs to be coerced and displayed as a plain string. Most
  539. notably, this happens when you display an object in an interactive
  540. console or in the admin.
  541. You'll always want to define this method; the default isn't very helpful
  542. at all.
  543. :meth:`~Model.get_absolute_url`
  544. This tells Django how to calculate the URL for an object. Django uses
  545. this in its admin interface, and any time it needs to figure out a URL
  546. for an object.
  547. Any object that has a URL that uniquely identifies it should define this
  548. method.
  549. .. _overriding-model-methods:
  550. Overriding predefined model methods
  551. -----------------------------------
  552. There's another set of :ref:`model methods <model-instance-methods>` that
  553. encapsulate a bunch of database behavior that you'll want to customize. In
  554. particular you'll often want to change the way :meth:`~Model.save` and
  555. :meth:`~Model.delete` work.
  556. You're free to override these methods (and any other model method) to alter
  557. behavior.
  558. A classic use-case for overriding the built-in methods is if you want something
  559. to happen whenever you save an object. For example (see
  560. :meth:`~Model.save` for documentation of the parameters it accepts)::
  561. from django.db import models
  562. class Blog(models.Model):
  563. name = models.CharField(max_length=100)
  564. tagline = models.TextField()
  565. def save(self, *args, **kwargs):
  566. do_something()
  567. super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
  568. do_something_else()
  569. You can also prevent saving::
  570. from django.db import models
  571. class Blog(models.Model):
  572. name = models.CharField(max_length=100)
  573. tagline = models.TextField()
  574. def save(self, *args, **kwargs):
  575. if self.name == "Yoko Ono's blog":
  576. return # Yoko shall never have her own blog!
  577. else:
  578. super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
  579. It's important to remember to call the superclass method -- that's
  580. that ``super(Blog, self).save(*args, **kwargs)`` business -- to ensure
  581. that the object still gets saved into the database. If you forget to
  582. call the superclass method, the default behavior won't happen and the
  583. database won't get touched.
  584. It's also important that you pass through the arguments that can be
  585. passed to the model method -- that's what the ``*args, **kwargs`` bit
  586. does. Django will, from time to time, extend the capabilities of
  587. built-in model methods, adding new arguments. If you use ``*args,
  588. **kwargs`` in your method definitions, you are guaranteed that your
  589. code will automatically support those arguments when they are added.
  590. .. admonition:: Overridden model methods are not called on bulk operations
  591. Note that the :meth:`~Model.delete()` method for an object is not
  592. necessarily called when :ref:`deleting objects in bulk using a
  593. QuerySet<topics-db-queries-delete>`. To ensure customized delete logic
  594. gets executed, you can use :data:`~django.db.models.signals.pre_delete`
  595. and/or :data:`~django.db.models.signals.post_delete` signals.
  596. Unfortunately, there isn't a workaround when
  597. :meth:`creating<django.db.models.query.QuerySet.bulk_create>` or
  598. :meth:`updating<django.db.models.query.QuerySet.update>` objects in bulk,
  599. since none of :meth:`~Model.save()`,
  600. :data:`~django.db.models.signals.pre_save`, and
  601. :data:`~django.db.models.signals.post_save` are called.
  602. Executing custom SQL
  603. --------------------
  604. Another common pattern is writing custom SQL statements in model methods and
  605. module-level methods. For more details on using raw SQL, see the documentation
  606. on :doc:`using raw SQL</topics/db/sql>`.
  607. .. _model-inheritance:
  608. Model inheritance
  609. =================
  610. Model inheritance in Django works almost identically to the way normal
  611. class inheritance works in Python. The only decision you have to make
  612. is whether you want the parent models to be models in their own right
  613. (with their own database tables), or if the parents are just holders
  614. of common information that will only be visible through the child
  615. models.
  616. There are three styles of inheritance that are possible in Django.
  617. 1. Often, you will just want to use the parent class to hold information that
  618. you don't want to have to type out for each child model. This class isn't
  619. going to ever be used in isolation, so :ref:`abstract-base-classes` are
  620. what you're after.
  621. 2. If you're subclassing an existing model (perhaps something from another
  622. application entirely) and want each model to have its own database table,
  623. :ref:`multi-table-inheritance` is the way to go.
  624. 3. Finally, if you only want to modify the Python-level behavior of a model,
  625. without changing the models fields in any way, you can use
  626. :ref:`proxy-models`.
  627. .. _abstract-base-classes:
  628. Abstract base classes
  629. ---------------------
  630. Abstract base classes are useful when you want to put some common
  631. information into a number of other models. You write your base class
  632. and put ``abstract=True`` in the :ref:`Meta <meta-options>`
  633. class. This model will then not be used to create any database
  634. table. Instead, when it is used as a base class for other models, its
  635. fields will be added to those of the child class. It is an error to
  636. have fields in the abstract base class with the same name as those in
  637. the child (and Django will raise an exception).
  638. An example::
  639. from django.db import models
  640. class CommonInfo(models.Model):
  641. name = models.CharField(max_length=100)
  642. age = models.PositiveIntegerField()
  643. class Meta:
  644. abstract = True
  645. class Student(CommonInfo):
  646. home_group = models.CharField(max_length=5)
  647. The ``Student`` model will have three fields: ``name``, ``age`` and
  648. ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
  649. model, since it is an abstract base class. It does not generate a database
  650. table or have a manager, and cannot be instantiated or saved directly.
  651. For many uses, this type of model inheritance will be exactly what you want.
  652. It provides a way to factor out common information at the Python level, whilst
  653. still only creating one database table per child model at the database level.
  654. ``Meta`` inheritance
  655. ~~~~~~~~~~~~~~~~~~~~
  656. When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
  657. inner class you declared in the base class available as an
  658. attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
  659. class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
  660. extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
  661. from django.db import models
  662. class CommonInfo(models.Model):
  663. # ...
  664. class Meta:
  665. abstract = True
  666. ordering = ['name']
  667. class Student(CommonInfo):
  668. # ...
  669. class Meta(CommonInfo.Meta):
  670. db_table = 'student_info'
  671. Django does make one adjustment to the :ref:`Meta <meta-options>` class of an abstract base
  672. class: before installing the :ref:`Meta <meta-options>` attribute, it sets ``abstract=False``.
  673. This means that children of abstract base classes don't automatically become
  674. abstract classes themselves. Of course, you can make an abstract base class
  675. that inherits from another abstract base class. You just need to remember to
  676. explicitly set ``abstract=True`` each time.
  677. Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
  678. abstract base class. For example, including ``db_table`` would mean that all
  679. the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
  680. the same database table, which is almost certainly not what you want.
  681. .. _abstract-related-name:
  682. Be careful with ``related_name``
  683. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  684. If you are using the :attr:`~django.db.models.ForeignKey.related_name` attribute on a ``ForeignKey`` or
  685. ``ManyToManyField``, you must always specify a *unique* reverse name for the
  686. field. This would normally cause a problem in abstract base classes, since the
  687. fields on this class are included into each of the child classes, with exactly
  688. the same values for the attributes (including :attr:`~django.db.models.ForeignKey.related_name`) each time.
  689. To work around this problem, when you are using :attr:`~django.db.models.ForeignKey.related_name` in an
  690. abstract base class (only), part of the name should contain
  691. ``'%(app_label)s'`` and ``'%(class)s'``.
  692. - ``'%(class)s'`` is replaced by the lower-cased name of the child class
  693. that the field is used in.
  694. - ``'%(app_label)s'`` is replaced by the lower-cased name of the app the child
  695. class is contained within. Each installed application name must be unique
  696. and the model class names within each app must also be unique, therefore the
  697. resulting name will end up being different.
  698. For example, given an app ``common/models.py``::
  699. from django.db import models
  700. class Base(models.Model):
  701. m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
  702. class Meta:
  703. abstract = True
  704. class ChildA(Base):
  705. pass
  706. class ChildB(Base):
  707. pass
  708. Along with another app ``rare/models.py``::
  709. from common.models import Base
  710. class ChildB(Base):
  711. pass
  712. The reverse name of the ``common.ChildA.m2m`` field will be
  713. ``common_childa_related``, whilst the reverse name of the
  714. ``common.ChildB.m2m`` field will be ``common_childb_related``, and finally the
  715. reverse name of the ``rare.ChildB.m2m`` field will be ``rare_childb_related``.
  716. It is up to you how you use the ``'%(class)s'`` and ``'%(app_label)s`` portion
  717. to construct your related name, but if you forget to use it, Django will raise
  718. errors when you validate your models (or run :djadmin:`migrate`).
  719. If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
  720. attribute for a field in an abstract base class, the default reverse name will
  721. be the name of the child class followed by ``'_set'``, just as it normally
  722. would be if you'd declared the field directly on the child class. For example,
  723. in the above code, if the :attr:`~django.db.models.ForeignKey.related_name`
  724. attribute was omitted, the reverse name for the ``m2m`` field would be
  725. ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``
  726. field.
  727. .. _multi-table-inheritance:
  728. Multi-table inheritance
  729. -----------------------
  730. The second type of model inheritance supported by Django is when each model in
  731. the hierarchy is a model all by itself. Each model corresponds to its own
  732. database table and can be queried and created individually. The inheritance
  733. relationship introduces links between the child model and each of its parents
  734. (via an automatically-created :class:`~django.db.models.OneToOneField`).
  735. For example::
  736. from django.db import models
  737. class Place(models.Model):
  738. name = models.CharField(max_length=50)
  739. address = models.CharField(max_length=80)
  740. class Restaurant(Place):
  741. serves_hot_dogs = models.BooleanField()
  742. serves_pizza = models.BooleanField()
  743. All of the fields of ``Place`` will also be available in ``Restaurant``,
  744. although the data will reside in a different database table. So these are both
  745. possible::
  746. >>> Place.objects.filter(name="Bob's Cafe")
  747. >>> Restaurant.objects.filter(name="Bob's Cafe")
  748. If you have a ``Place`` that is also a ``Restaurant``, you can get from the
  749. ``Place`` object to the ``Restaurant`` object by using the lower-case version
  750. of the model name::
  751. >>> p = Place.objects.get(id=12)
  752. # If p is a Restaurant object, this will give the child class:
  753. >>> p.restaurant
  754. <Restaurant: ...>
  755. However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
  756. created directly as a ``Place`` object or was the parent of some other class),
  757. referring to ``p.restaurant`` would raise a Restaurant.DoesNotExist exception.
  758. ``Meta`` and multi-table inheritance
  759. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  760. In the multi-table inheritance situation, it doesn't make sense for a child
  761. class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
  762. have already been applied to the parent class and applying them again would
  763. normally only lead to contradictory behavior (this is in contrast with the
  764. abstract base class case, where the base class doesn't exist in its own
  765. right).
  766. So a child model does not have access to its parent's :ref:`Meta
  767. <meta-options>` class. However, there are a few limited cases where the child
  768. inherits behavior from the parent: if the child does not specify an
  769. :attr:`~django.db.models.Options.ordering` attribute or a
  770. :attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit
  771. these from its parent.
  772. If the parent has an ordering and you don't want the child to have any natural
  773. ordering, you can explicitly disable it::
  774. class ChildModel(ParentModel):
  775. # ...
  776. class Meta:
  777. # Remove parent's ordering effect
  778. ordering = []
  779. Inheritance and reverse relations
  780. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  781. Because multi-table inheritance uses an implicit
  782. :class:`~django.db.models.OneToOneField` to link the child and
  783. the parent, it's possible to move from the parent down to the child,
  784. as in the above example. However, this uses up the name that is the
  785. default :attr:`~django.db.models.ForeignKey.related_name` value for
  786. :class:`~django.db.models.ForeignKey` and
  787. :class:`~django.db.models.ManyToManyField` relations. If you
  788. are putting those types of relations on a subclass of another model,
  789. you **must** specify the
  790. :attr:`~django.db.models.ForeignKey.related_name` attribute on each
  791. such field. If you forget, Django will raise an error when you run
  792. :djadmin:`validate` or :djadmin:`migrate`.
  793. For example, using the above ``Place`` class again, let's create another
  794. subclass with a :class:`~django.db.models.ManyToManyField`::
  795. class Supplier(Place):
  796. # Must specify related_name on all relations.
  797. customers = models.ManyToManyField(Restaurant, related_name='provider')
  798. Specifying the parent link field
  799. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  800. As mentioned, Django will automatically create a
  801. :class:`~django.db.models.OneToOneField` linking your child
  802. class back any non-abstract parent models. If you want to control the
  803. name of the attribute linking back to the parent, you can create your
  804. own :class:`~django.db.models.OneToOneField` and set
  805. :attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`
  806. to indicate that your field is the link back to the parent class.
  807. .. _proxy-models:
  808. Proxy models
  809. ------------
  810. When using :ref:`multi-table inheritance <multi-table-inheritance>`, a new
  811. database table is created for each subclass of a model. This is usually the
  812. desired behavior, since the subclass needs a place to store any additional
  813. data fields that are not present on the base class. Sometimes, however, you
  814. only want to change the Python behavior of a model -- perhaps to change the
  815. default manager, or add a new method.
  816. This is what proxy model inheritance is for: creating a *proxy* for the
  817. original model. You can create, delete and update instances of the proxy model
  818. and all the data will be saved as if you were using the original (non-proxied)
  819. model. The difference is that you can change things like the default model
  820. ordering or the default manager in the proxy, without having to alter the
  821. original.
  822. Proxy models are declared like normal models. You tell Django that it's a
  823. proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
  824. the ``Meta`` class to ``True``.
  825. For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
  826. from django.db import models
  827. class Person(models.Model):
  828. first_name = models.CharField(max_length=30)
  829. last_name = models.CharField(max_length=30)
  830. class MyPerson(Person):
  831. class Meta:
  832. proxy = True
  833. def do_something(self):
  834. # ...
  835. pass
  836. The ``MyPerson`` class operates on the same database table as its parent
  837. ``Person`` class. In particular, any new instances of ``Person`` will also be
  838. accessible through ``MyPerson``, and vice-versa::
  839. >>> p = Person.objects.create(first_name="foobar")
  840. >>> MyPerson.objects.get(first_name="foobar")
  841. <MyPerson: foobar>
  842. You could also use a proxy model to define a different default ordering on
  843. a model. You might not always want to order the ``Person`` model, but regularly
  844. order by the ``last_name`` attribute when you use the proxy. This is easy::
  845. class OrderedPerson(Person):
  846. class Meta:
  847. ordering = ["last_name"]
  848. proxy = True
  849. Now normal ``Person`` queries will be unordered
  850. and ``OrderedPerson`` queries will be ordered by ``last_name``.
  851. QuerySets still return the model that was requested
  852. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  853. There is no way to have Django return, say, a ``MyPerson`` object whenever you
  854. query for ``Person`` objects. A queryset for ``Person`` objects will return
  855. those types of objects. The whole point of proxy objects is that code relying
  856. on the original ``Person`` will use those and your own code can use the
  857. extensions you included (that no other code is relying on anyway). It is not
  858. a way to replace the ``Person`` (or any other) model everywhere with something
  859. of your own creation.
  860. Base class restrictions
  861. ~~~~~~~~~~~~~~~~~~~~~~~
  862. A proxy model must inherit from exactly one non-abstract model class. You
  863. can't inherit from multiple non-abstract models as the proxy model doesn't
  864. provide any connection between the rows in the different database tables. A
  865. proxy model can inherit from any number of abstract model classes, providing
  866. they do *not* define any model fields.
  867. Proxy models inherit any ``Meta`` options that they don't define from their
  868. non-abstract model parent (the model they are proxying for).
  869. Proxy model managers
  870. ~~~~~~~~~~~~~~~~~~~~
  871. If you don't specify any model managers on a proxy model, it inherits the
  872. managers from its model parents. If you define a manager on the proxy model,
  873. it will become the default, although any managers defined on the parent
  874. classes will still be available.
  875. Continuing our example from above, you could change the default manager used
  876. when you query the ``Person`` model like this::
  877. from django.db import models
  878. class NewManager(models.Manager):
  879. # ...
  880. pass
  881. class MyPerson(Person):
  882. objects = NewManager()
  883. class Meta:
  884. proxy = True
  885. If you wanted to add a new manager to the Proxy, without replacing the
  886. existing default, you can use the techniques described in the :ref:`custom
  887. manager <custom-managers-and-inheritance>` documentation: create a base class
  888. containing the new managers and inherit that after the primary base class::
  889. # Create an abstract class for the new manager.
  890. class ExtraManagers(models.Model):
  891. secondary = NewManager()
  892. class Meta:
  893. abstract = True
  894. class MyPerson(Person, ExtraManagers):
  895. class Meta:
  896. proxy = True
  897. You probably won't need to do this very often, but, when you do, it's
  898. possible.
  899. .. _proxy-vs-unmanaged-models:
  900. Differences between proxy inheritance and unmanaged models
  901. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  902. Proxy model inheritance might look fairly similar to creating an unmanaged
  903. model, using the :attr:`~django.db.models.Options.managed` attribute on a
  904. model's ``Meta`` class. The two alternatives are not quite the same and it's
  905. worth considering which one you should use.
  906. One difference is that you can (and, in fact, must unless you want an empty
  907. model) specify model fields on models with ``Meta.managed=False``. You could,
  908. with careful setting of :attr:`Meta.db_table
  909. <django.db.models.Options.db_table>` create an unmanaged model that shadowed
  910. an existing model and add Python methods to it. However, that would be very
  911. repetitive and fragile as you need to keep both copies synchronized if you
  912. make any changes.
  913. The other difference that is more important for proxy models, is how model
  914. managers are handled. Proxy models are intended to behave exactly like the
  915. model they are proxying for. So they inherit the parent model's managers,
  916. including the default manager. In the normal multi-table model inheritance
  917. case, children do not inherit managers from their parents as the custom
  918. managers aren't always appropriate when extra fields are involved. The
  919. :ref:`manager documentation <custom-managers-and-inheritance>` has more
  920. details about this latter case.
  921. When these two features were implemented, attempts were made to squash them
  922. into a single option. It turned out that interactions with inheritance, in
  923. general, and managers, in particular, made the API very complicated and
  924. potentially difficult to understand and use. It turned out that two options
  925. were needed in any case, so the current separation arose.
  926. So, the general rules are:
  927. 1. If you are mirroring an existing model or database table and don't want
  928. all the original database table columns, use ``Meta.managed=False``.
  929. That option is normally useful for modeling database views and tables
  930. not under the control of Django.
  931. 2. If you are wanting to change the Python-only behavior of a model, but
  932. keep all the same fields as in the original, use ``Meta.proxy=True``.
  933. This sets things up so that the proxy model is an exact copy of the
  934. storage structure of the original model when data is saved.
  935. Multiple inheritance
  936. --------------------
  937. Just as with Python's subclassing, it's possible for a Django model to inherit
  938. from multiple parent models. Keep in mind that normal Python name resolution
  939. rules apply. The first base class that a particular name (e.g. :ref:`Meta
  940. <meta-options>`) appears in will be the one that is used; for example, this
  941. means that if multiple parents contain a :ref:`Meta <meta-options>` class,
  942. only the first one is going to be used, and all others will be ignored.
  943. Generally, you won't need to inherit from multiple parents. The main use-case
  944. where this is useful is for "mix-in" classes: adding a particular extra
  945. field or method to every class that inherits the mix-in. Try to keep your
  946. inheritance hierarchies as simple and straightforward as possible so that you
  947. won't have to struggle to work out where a particular piece of information is
  948. coming from.
  949. Field name "hiding" is not permitted
  950. -------------------------------------
  951. In normal Python class inheritance, it is permissible for a child class to
  952. override any attribute from the parent class. In Django, this is not permitted
  953. for attributes that are :class:`~django.db.models.Field` instances (at
  954. least, not at the moment). If a base class has a field called ``author``, you
  955. cannot create another model field called ``author`` in any class that inherits
  956. from that base class.
  957. Overriding fields in a parent model leads to difficulties in areas such as
  958. initializing new instances (specifying which field is being initialized in
  959. ``Model.__init__``) and serialization. These are features which normal Python
  960. class inheritance doesn't have to deal with in quite the same way, so the
  961. difference between Django model inheritance and Python class inheritance isn't
  962. arbitrary.
  963. This restriction only applies to attributes which are
  964. :class:`~django.db.models.Field` instances. Normal Python attributes
  965. can be overridden if you wish. It also only applies to the name of the
  966. attribute as Python sees it: if you are manually specifying the database
  967. column name, you can have the same column name appearing in both a child and
  968. an ancestor model for multi-table inheritance (they are columns in two
  969. different database tables).
  970. Django will raise a :exc:`~django.core.exceptions.FieldError` if you override
  971. any model field in any ancestor model.