models.txt 49 KB

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