models.txt 50 KB

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