models.txt 50 KB

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