models.txt 54 KB

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