models.txt 49 KB

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