models.txt 50 KB

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