models.txt 53 KB

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