models.txt 56 KB

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