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

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.