models.txt 57 KB

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