models.txt 50 KB

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