1. ========================
    
  2. Model instance reference
    
  3. ========================
    
  4. 
    
  5. .. currentmodule:: django.db.models
    
  6. 
    
  7. This document describes the details of the ``Model`` API. It builds on the
    
  8. material presented in the :doc:`model </topics/db/models>` and :doc:`database
    
  9. query </topics/db/queries>` guides, so you'll probably want to read and
    
  10. understand those documents before reading this one.
    
  11. 
    
  12. Throughout this reference we'll use the :ref:`example blog models
    
  13. <queryset-model-example>` presented in the :doc:`database query guide
    
  14. </topics/db/queries>`.
    
  15. 
    
  16. Creating objects
    
  17. ================
    
  18. 
    
  19. To create a new instance of a model, instantiate it like any other Python
    
  20. class:
    
  21. 
    
  22. .. class:: Model(**kwargs)
    
  23. 
    
  24. The keyword arguments are the names of the fields you've defined on your model.
    
  25. Note that instantiating a model in no way touches your database; for that, you
    
  26. need to :meth:`~Model.save()`.
    
  27. 
    
  28. .. note::
    
  29. 
    
  30.     You may be tempted to customize the model by overriding the ``__init__``
    
  31.     method. If you do so, however, take care not to change the calling
    
  32.     signature as any change may prevent the model instance from being saved.
    
  33.     Rather than overriding ``__init__``, try using one of these approaches:
    
  34. 
    
  35.     #. Add a classmethod on the model class::
    
  36. 
    
  37.         from django.db import models
    
  38. 
    
  39.         class Book(models.Model):
    
  40.             title = models.CharField(max_length=100)
    
  41. 
    
  42.             @classmethod
    
  43.             def create(cls, title):
    
  44.                 book = cls(title=title)
    
  45.                 # do something with the book
    
  46.                 return book
    
  47. 
    
  48.         book = Book.create("Pride and Prejudice")
    
  49. 
    
  50.     #. Add a method on a custom manager (usually preferred)::
    
  51. 
    
  52.         class BookManager(models.Manager):
    
  53.             def create_book(self, title):
    
  54.                 book = self.create(title=title)
    
  55.                 # do something with the book
    
  56.                 return book
    
  57. 
    
  58.         class Book(models.Model):
    
  59.             title = models.CharField(max_length=100)
    
  60. 
    
  61.             objects = BookManager()
    
  62. 
    
  63.         book = Book.objects.create_book("Pride and Prejudice")
    
  64. 
    
  65. Customizing model loading
    
  66. -------------------------
    
  67. 
    
  68. .. classmethod:: Model.from_db(db, field_names, values)
    
  69. 
    
  70. The ``from_db()`` method can be used to customize model instance creation
    
  71. when loading from the database.
    
  72. 
    
  73. The ``db`` argument contains the database alias for the database the model
    
  74. is loaded from, ``field_names`` contains the names of all loaded fields, and
    
  75. ``values`` contains the loaded values for each field in ``field_names``. The
    
  76. ``field_names`` are in the same order as the ``values``. If all of the model's
    
  77. fields are present, then ``values`` are guaranteed to be in the order
    
  78. ``__init__()`` expects them. That is, the instance can be created by
    
  79. ``cls(*values)``. If any fields are deferred, they won't appear in
    
  80. ``field_names``. In that case, assign a value of ``django.db.models.DEFERRED``
    
  81. to each of the missing fields.
    
  82. 
    
  83. In addition to creating the new model, the ``from_db()`` method must set the
    
  84. ``adding`` and ``db`` flags in the new instance's :attr:`~Model._state` attribute.
    
  85. 
    
  86. Below is an example showing how to record the initial values of fields that
    
  87. are loaded from the database::
    
  88. 
    
  89.     from django.db.models import DEFERRED
    
  90. 
    
  91.     @classmethod
    
  92.     def from_db(cls, db, field_names, values):
    
  93.         # Default implementation of from_db() (subject to change and could
    
  94.         # be replaced with super()).
    
  95.         if len(values) != len(cls._meta.concrete_fields):
    
  96.             values = list(values)
    
  97.             values.reverse()
    
  98.             values = [
    
  99.                 values.pop() if f.attname in field_names else DEFERRED
    
  100.                 for f in cls._meta.concrete_fields
    
  101.             ]
    
  102.         instance = cls(*values)
    
  103.         instance._state.adding = False
    
  104.         instance._state.db = db
    
  105.         # customization to store the original field values on the instance
    
  106.         instance._loaded_values = dict(
    
  107.             zip(field_names, (value for value in values if value is not DEFERRED))
    
  108.         )
    
  109.         return instance
    
  110. 
    
  111.     def save(self, *args, **kwargs):
    
  112.         # Check how the current values differ from ._loaded_values. For example,
    
  113.         # prevent changing the creator_id of the model. (This example doesn't
    
  114.         # support cases where 'creator_id' is deferred).
    
  115.         if not self._state.adding and (
    
  116.                 self.creator_id != self._loaded_values['creator_id']):
    
  117.             raise ValueError("Updating the value of creator isn't allowed")
    
  118.         super().save(*args, **kwargs)
    
  119. 
    
  120. The example above shows a full ``from_db()`` implementation to clarify how that
    
  121. is done. In this case it would be possible to use a ``super()`` call in the
    
  122. ``from_db()`` method.
    
  123. 
    
  124. Refreshing objects from database
    
  125. ================================
    
  126. 
    
  127. If you delete a field from a model instance, accessing it again reloads the
    
  128. value from the database::
    
  129. 
    
  130.     >>> obj = MyModel.objects.first()
    
  131.     >>> del obj.field
    
  132.     >>> obj.field  # Loads the field from the database
    
  133. 
    
  134. .. method:: Model.refresh_from_db(using=None, fields=None)
    
  135. 
    
  136. If you need to reload a model's values from the database, you can use the
    
  137. ``refresh_from_db()`` method. When this method is called without arguments the
    
  138. following is done:
    
  139. 
    
  140. #. All non-deferred fields of the model are updated to the values currently
    
  141.    present in the database.
    
  142. #. Any cached relations are cleared from the reloaded instance.
    
  143. 
    
  144. Only fields of the model are reloaded from the database. Other
    
  145. database-dependent values such as annotations aren't reloaded. Any
    
  146. :func:`@cached_property <django.utils.functional.cached_property>` attributes
    
  147. aren't cleared either.
    
  148. 
    
  149. The reloading happens from the database the instance was loaded from, or from
    
  150. the default database if the instance wasn't loaded from the database. The
    
  151. ``using`` argument can be used to force the database used for reloading.
    
  152. 
    
  153. It is possible to force the set of fields to be loaded by using the ``fields``
    
  154. argument.
    
  155. 
    
  156. For example, to test that an ``update()`` call resulted in the expected
    
  157. update, you could write a test similar to this::
    
  158. 
    
  159.     def test_update_result(self):
    
  160.         obj = MyModel.objects.create(val=1)
    
  161.         MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
    
  162.         # At this point obj.val is still 1, but the value in the database
    
  163.         # was updated to 2. The object's updated value needs to be reloaded
    
  164.         # from the database.
    
  165.         obj.refresh_from_db()
    
  166.         self.assertEqual(obj.val, 2)
    
  167. 
    
  168. Note that when deferred fields are accessed, the loading of the deferred
    
  169. field's value happens through this method. Thus it is possible to customize
    
  170. the way deferred loading happens. The example below shows how one can reload
    
  171. all of the instance's fields when a deferred field is reloaded::
    
  172. 
    
  173.     class ExampleModel(models.Model):
    
  174.         def refresh_from_db(self, using=None, fields=None, **kwargs):
    
  175.             # fields contains the name of the deferred field to be
    
  176.             # loaded.
    
  177.             if fields is not None:
    
  178.                 fields = set(fields)
    
  179.                 deferred_fields = self.get_deferred_fields()
    
  180.                 # If any deferred field is going to be loaded
    
  181.                 if fields.intersection(deferred_fields):
    
  182.                     # then load all of them
    
  183.                     fields = fields.union(deferred_fields)
    
  184.             super().refresh_from_db(using, fields, **kwargs)
    
  185. 
    
  186. .. method:: Model.get_deferred_fields()
    
  187. 
    
  188. A helper method that returns a set containing the attribute names of all those
    
  189. fields that are currently deferred for this model.
    
  190. 
    
  191. .. _validating-objects:
    
  192. 
    
  193. Validating objects
    
  194. ==================
    
  195. 
    
  196. There are four steps involved in validating a model:
    
  197. 
    
  198. 1. Validate the model fields - :meth:`Model.clean_fields()`
    
  199. 2. Validate the model as a whole - :meth:`Model.clean()`
    
  200. 3. Validate the field uniqueness - :meth:`Model.validate_unique()`
    
  201. 4. Validate the constraints - :meth:`Model.validate_constraints`
    
  202. 
    
  203. All four steps are performed when you call a model's :meth:`~Model.full_clean`
    
  204. method.
    
  205. 
    
  206. When you use a :class:`~django.forms.ModelForm`, the call to
    
  207. :meth:`~django.forms.Form.is_valid()` will perform these validation steps for
    
  208. all the fields that are included on the form. See the :doc:`ModelForm
    
  209. documentation </topics/forms/modelforms>` for more information. You should only
    
  210. need to call a model's :meth:`~Model.full_clean()` method if you plan to handle
    
  211. validation errors yourself, or if you have excluded fields from the
    
  212. :class:`~django.forms.ModelForm` that require validation.
    
  213. 
    
  214. .. warning::
    
  215. 
    
  216.     Constraints containing :class:`~django.db.models.JSONField` may not raise
    
  217.     validation errors as key, index, and path transforms have many
    
  218.     database-specific caveats. This :ticket:`may be fully supported later
    
  219.     <34059>`.
    
  220. 
    
  221.     You should always check that there are no log messages, in the
    
  222.     ``django.db.models`` logger, like *"Got a database error calling check() on
    
  223.     …"* to confirm it's validated properly.
    
  224. 
    
  225. .. versionchanged:: 4.1
    
  226. 
    
  227.     In older versions, constraints were not checked during the model
    
  228.     validation.
    
  229. 
    
  230. .. method:: Model.full_clean(exclude=None, validate_unique=True, validate_constraints=True)
    
  231. 
    
  232. This method calls :meth:`Model.clean_fields()`, :meth:`Model.clean()`,
    
  233. :meth:`Model.validate_unique()` (if ``validate_unique`` is ``True``),  and
    
  234. :meth:`Model.validate_constraints()` (if ``validate_constraints`` is ``True``)
    
  235. in that order and raises a :exc:`~django.core.exceptions.ValidationError` that
    
  236. has a ``message_dict`` attribute containing errors from all four stages.
    
  237. 
    
  238. The optional ``exclude`` argument can be used to provide a ``set`` of field
    
  239. names that can be excluded from validation and cleaning.
    
  240. :class:`~django.forms.ModelForm` uses this argument to exclude fields that
    
  241. aren't present on your form from being validated since any errors raised could
    
  242. not be corrected by the user.
    
  243. 
    
  244. Note that ``full_clean()`` will *not* be called automatically when you call
    
  245. your model's :meth:`~Model.save()` method. You'll need to call it manually
    
  246. when you want to run one-step model validation for your own manually created
    
  247. models. For example::
    
  248. 
    
  249.     from django.core.exceptions import ValidationError
    
  250.     try:
    
  251.         article.full_clean()
    
  252.     except ValidationError as e:
    
  253.         # Do something based on the errors contained in e.message_dict.
    
  254.         # Display them to a user, or handle them programmatically.
    
  255.         pass
    
  256. 
    
  257. The first step ``full_clean()`` performs is to clean each individual field.
    
  258. 
    
  259. .. versionchanged:: 4.1
    
  260. 
    
  261.     The ``validate_constraints`` argument was added.
    
  262. 
    
  263. .. versionchanged:: 4.1
    
  264. 
    
  265.     An ``exclude`` value is now converted to a ``set`` rather than a ``list``.
    
  266. 
    
  267. .. method:: Model.clean_fields(exclude=None)
    
  268. 
    
  269. This method will validate all fields on your model. The optional ``exclude``
    
  270. argument lets you provide a ``set`` of field names to exclude from validation.
    
  271. It will raise a :exc:`~django.core.exceptions.ValidationError` if any fields
    
  272. fail validation.
    
  273. 
    
  274. The second step ``full_clean()`` performs is to call :meth:`Model.clean()`.
    
  275. This method should be overridden to perform custom validation on your model.
    
  276. 
    
  277. .. method:: Model.clean()
    
  278. 
    
  279. This method should be used to provide custom model validation, and to modify
    
  280. attributes on your model if desired. For instance, you could use it to
    
  281. automatically provide a value for a field, or to do validation that requires
    
  282. access to more than a single field::
    
  283. 
    
  284.     import datetime
    
  285.     from django.core.exceptions import ValidationError
    
  286.     from django.db import models
    
  287.     from django.utils.translation import gettext_lazy as _
    
  288. 
    
  289.     class Article(models.Model):
    
  290.         ...
    
  291.         def clean(self):
    
  292.             # Don't allow draft entries to have a pub_date.
    
  293.             if self.status == 'draft' and self.pub_date is not None:
    
  294.                 raise ValidationError(_('Draft entries may not have a publication date.'))
    
  295.             # Set the pub_date for published items if it hasn't been set already.
    
  296.             if self.status == 'published' and self.pub_date is None:
    
  297.                 self.pub_date = datetime.date.today()
    
  298. 
    
  299. Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()``
    
  300. method is not invoked when you call your model's :meth:`~Model.save()` method.
    
  301. 
    
  302. In the above example, the :exc:`~django.core.exceptions.ValidationError`
    
  303. exception raised by ``Model.clean()`` was instantiated with a string, so it
    
  304. will be stored in a special error dictionary key,
    
  305. :data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors
    
  306. that are tied to the entire model instead of to a specific field::
    
  307. 
    
  308.     from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
    
  309.     try:
    
  310.         article.full_clean()
    
  311.     except ValidationError as e:
    
  312.         non_field_errors = e.message_dict[NON_FIELD_ERRORS]
    
  313. 
    
  314. To assign exceptions to a specific field, instantiate the
    
  315. :exc:`~django.core.exceptions.ValidationError` with a dictionary, where the
    
  316. keys are the field names. We could update the previous example to assign the
    
  317. error to the ``pub_date`` field::
    
  318. 
    
  319.     class Article(models.Model):
    
  320.         ...
    
  321.         def clean(self):
    
  322.             # Don't allow draft entries to have a pub_date.
    
  323.             if self.status == 'draft' and self.pub_date is not None:
    
  324.                 raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')})
    
  325.             ...
    
  326. 
    
  327. If you detect errors in multiple fields during ``Model.clean()``, you can also
    
  328. pass a dictionary mapping field names to errors::
    
  329. 
    
  330.     raise ValidationError({
    
  331.         'title': ValidationError(_('Missing title.'), code='required'),
    
  332.         'pub_date': ValidationError(_('Invalid date.'), code='invalid'),
    
  333.     })
    
  334. 
    
  335. Then, ``full_clean()`` will check unique constraints on your model.
    
  336. 
    
  337. .. admonition:: How to raise field-specific validation errors if those fields don't appear in a ``ModelForm``
    
  338. 
    
  339.     You can't raise validation errors in ``Model.clean()`` for fields that
    
  340.     don't appear in a model form (a form may limit its fields using
    
  341.     ``Meta.fields`` or ``Meta.exclude``). Doing so will raise a ``ValueError``
    
  342.     because the validation error won't be able to be associated with the
    
  343.     excluded field.
    
  344. 
    
  345.     To work around this dilemma, instead override :meth:`Model.clean_fields()
    
  346.     <django.db.models.Model.clean_fields>` as it receives the list of fields
    
  347.     that are excluded from validation. For example::
    
  348. 
    
  349.         class Article(models.Model):
    
  350.             ...
    
  351.             def clean_fields(self, exclude=None):
    
  352.                 super().clean_fields(exclude=exclude)
    
  353.                 if self.status == 'draft' and self.pub_date is not None:
    
  354.                     if exclude and 'status' in exclude:
    
  355.                         raise ValidationError(
    
  356.                             _('Draft entries may not have a publication date.')
    
  357.                         )
    
  358.                     else:
    
  359.                         raise ValidationError({
    
  360.                             'status': _(
    
  361.                                 'Set status to draft if there is not a '
    
  362.                                 'publication date.'
    
  363.                              ),
    
  364.                         })
    
  365. 
    
  366. .. method:: Model.validate_unique(exclude=None)
    
  367. 
    
  368. This method is similar to :meth:`~Model.clean_fields`, but validates
    
  369. uniqueness constraints defined via :attr:`.Field.unique`,
    
  370. :attr:`.Field.unique_for_date`, :attr:`.Field.unique_for_month`,
    
  371. :attr:`.Field.unique_for_year`, or :attr:`Meta.unique_together
    
  372. <django.db.models.Options.unique_together>` on your model instead of individual
    
  373. field values. The optional ``exclude`` argument allows you to provide a ``set``
    
  374. of field names to exclude from validation. It will raise a
    
  375. :exc:`~django.core.exceptions.ValidationError` if any fields fail validation.
    
  376. 
    
  377. :class:`~django.db.models.UniqueConstraint`\s defined in the
    
  378. :attr:`Meta.constraints <django.db.models.Options.constraints>` are validated
    
  379. by :meth:`Model.validate_constraints`.
    
  380. 
    
  381. Note that if you provide an ``exclude`` argument to ``validate_unique()``, any
    
  382. :attr:`~django.db.models.Options.unique_together` constraint involving one of
    
  383. the fields you provided will not be checked.
    
  384. 
    
  385. Finally, ``full_clean()`` will check any other constraints on your model.
    
  386. 
    
  387. .. versionchanged:: 4.1
    
  388. 
    
  389.     In older versions, :class:`~django.db.models.UniqueConstraint`\s were
    
  390.     validated by ``validate_unique()``.
    
  391. 
    
  392. .. method:: Model.validate_constraints(exclude=None)
    
  393. 
    
  394. .. versionadded:: 4.1
    
  395. 
    
  396. This method validates all constraints defined in
    
  397. :attr:`Meta.constraints <django.db.models.Options.constraints>`. The
    
  398. optional ``exclude`` argument allows you to provide a ``set`` of field names to
    
  399. exclude from validation. It will raise a
    
  400. :exc:`~django.core.exceptions.ValidationError` if any constraints fail
    
  401. validation.
    
  402. 
    
  403. Saving objects
    
  404. ==============
    
  405. 
    
  406. To save an object back to the database, call ``save()``:
    
  407. 
    
  408. .. method:: Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)
    
  409. 
    
  410. For details on using the ``force_insert`` and ``force_update`` arguments, see
    
  411. :ref:`ref-models-force-insert`. Details about the ``update_fields`` argument
    
  412. can be found in the :ref:`ref-models-update-fields` section.
    
  413. 
    
  414. If you want customized saving behavior, you can override this ``save()``
    
  415. method. See :ref:`overriding-model-methods` for more details.
    
  416. 
    
  417. The model save process also has some subtleties; see the sections below.
    
  418. 
    
  419. Auto-incrementing primary keys
    
  420. ------------------------------
    
  421. 
    
  422. If a model has an :class:`~django.db.models.AutoField` — an auto-incrementing
    
  423. primary key — then that auto-incremented value will be calculated and saved as
    
  424. an attribute on your object the first time you call ``save()``::
    
  425. 
    
  426.     >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
    
  427.     >>> b2.id     # Returns None, because b2 doesn't have an ID yet.
    
  428.     >>> b2.save()
    
  429.     >>> b2.id     # Returns the ID of your new object.
    
  430. 
    
  431. There's no way to tell what the value of an ID will be before you call
    
  432. ``save()``, because that value is calculated by your database, not by Django.
    
  433. 
    
  434. For convenience, each model has an :class:`~django.db.models.AutoField` named
    
  435. ``id`` by default unless you explicitly specify ``primary_key=True`` on a field
    
  436. in your model. See the documentation for :class:`~django.db.models.AutoField`
    
  437. for more details.
    
  438. 
    
  439. The ``pk`` property
    
  440. ~~~~~~~~~~~~~~~~~~~
    
  441. 
    
  442. .. attribute:: Model.pk
    
  443. 
    
  444. Regardless of whether you define a primary key field yourself, or let Django
    
  445. supply one for you, each model will have a property called ``pk``. It behaves
    
  446. like a normal attribute on the model, but is actually an alias for whichever
    
  447. attribute is the primary key field for the model. You can read and set this
    
  448. value, just as you would for any other attribute, and it will update the
    
  449. correct field in the model.
    
  450. 
    
  451. Explicitly specifying auto-primary-key values
    
  452. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  453. 
    
  454. If a model has an :class:`~django.db.models.AutoField` but you want to define a
    
  455. new object's ID explicitly when saving, define it explicitly before saving,
    
  456. rather than relying on the auto-assignment of the ID::
    
  457. 
    
  458.     >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
    
  459.     >>> b3.id     # Returns 3.
    
  460.     >>> b3.save()
    
  461.     >>> b3.id     # Returns 3.
    
  462. 
    
  463. If you assign auto-primary-key values manually, make sure not to use an
    
  464. already-existing primary-key value! If you create a new object with an explicit
    
  465. primary-key value that already exists in the database, Django will assume you're
    
  466. changing the existing record rather than creating a new one.
    
  467. 
    
  468. Given the above ``'Cheddar Talk'`` blog example, this example would override the
    
  469. previous record in the database::
    
  470. 
    
  471.     b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
    
  472.     b4.save()  # Overrides the previous blog with ID=3!
    
  473. 
    
  474. See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this
    
  475. happens.
    
  476. 
    
  477. Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
    
  478. objects, when you're confident you won't have primary-key collision.
    
  479. 
    
  480. If you're using PostgreSQL, the sequence associated with the primary key might
    
  481. need to be updated; see :ref:`manually-specified-autoincrement-pk`.
    
  482. 
    
  483. What happens when you save?
    
  484. ---------------------------
    
  485. 
    
  486. When you save an object, Django performs the following steps:
    
  487. 
    
  488. #. **Emit a pre-save signal.** The :data:`~django.db.models.signals.pre_save`
    
  489.    signal is sent, allowing any functions listening for that signal to do
    
  490.    something.
    
  491. 
    
  492. #. **Preprocess the data.** Each field's
    
  493.    :meth:`~django.db.models.Field.pre_save` method is called to perform any
    
  494.    automated data modification that's needed. For example, the date/time fields
    
  495.    override ``pre_save()`` to implement
    
  496.    :attr:`~django.db.models.DateField.auto_now_add` and
    
  497.    :attr:`~django.db.models.DateField.auto_now`.
    
  498. 
    
  499. #. **Prepare the data for the database.** Each field's
    
  500.    :meth:`~django.db.models.Field.get_db_prep_save` method is asked to provide
    
  501.    its current value in a data type that can be written to the database.
    
  502. 
    
  503.    Most fields don't require data preparation. Simple data types, such as
    
  504.    integers and strings, are 'ready to write' as a Python object. However, more
    
  505.    complex data types often require some modification.
    
  506. 
    
  507.    For example, :class:`~django.db.models.DateField` fields use a Python
    
  508.    ``datetime`` object to store data. Databases don't store ``datetime``
    
  509.    objects, so the field value must be converted into an ISO-compliant date
    
  510.    string for insertion into the database.
    
  511. 
    
  512. #. **Insert the data into the database.** The preprocessed, prepared data is
    
  513.    composed into an SQL statement for insertion into the database.
    
  514. 
    
  515. #. **Emit a post-save signal.** The :data:`~django.db.models.signals.post_save`
    
  516.    signal is sent, allowing any functions listening for that signal to do
    
  517.    something.
    
  518. 
    
  519. How Django knows to UPDATE vs. INSERT
    
  520. -------------------------------------
    
  521. 
    
  522. You may have noticed Django database objects use the same ``save()`` method
    
  523. for creating and changing objects. Django abstracts the need to use ``INSERT``
    
  524. or ``UPDATE`` SQL statements. Specifically, when you call ``save()`` and the
    
  525. object's primary key attribute does **not** define a
    
  526. :attr:`~django.db.models.Field.default`, Django follows this algorithm:
    
  527. 
    
  528. * If the object's primary key attribute is set to a value that evaluates to
    
  529.   ``True`` (i.e., a value other than ``None`` or the empty string), Django
    
  530.   executes an ``UPDATE``.
    
  531. * If the object's primary key attribute is *not* set or if the ``UPDATE``
    
  532.   didn't update anything (e.g. if primary key is set to a value that doesn't
    
  533.   exist in the database), Django executes an ``INSERT``.
    
  534. 
    
  535. If the object's primary key attribute defines a
    
  536. :attr:`~django.db.models.Field.default` then Django executes an ``UPDATE`` if
    
  537. it is an existing model instance and primary key is set to a value that exists
    
  538. in the database. Otherwise, Django executes an ``INSERT``.
    
  539. 
    
  540. The one gotcha here is that you should be careful not to specify a primary-key
    
  541. value explicitly when saving new objects, if you cannot guarantee the
    
  542. primary-key value is unused. For more on this nuance, see `Explicitly specifying
    
  543. auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below.
    
  544. 
    
  545. In Django 1.5 and earlier, Django did a ``SELECT`` when the primary key
    
  546. attribute was set. If the ``SELECT`` found a row, then Django did an ``UPDATE``,
    
  547. otherwise it did an ``INSERT``. The old algorithm results in one more query in
    
  548. the ``UPDATE`` case. There are some rare cases where the database doesn't
    
  549. report that a row was updated even if the database contains a row for the
    
  550. object's primary key value. An example is the PostgreSQL ``ON UPDATE`` trigger
    
  551. which returns ``NULL``. In such cases it is possible to revert to the old
    
  552. algorithm by setting the :attr:`~django.db.models.Options.select_on_save`
    
  553. option to ``True``.
    
  554. 
    
  555. .. _ref-models-force-insert:
    
  556. 
    
  557. Forcing an INSERT or UPDATE
    
  558. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  559. 
    
  560. In some rare circumstances, it's necessary to be able to force the
    
  561. :meth:`~Model.save()` method to perform an SQL ``INSERT`` and not fall back to
    
  562. doing an ``UPDATE``. Or vice-versa: update, if possible, but not insert a new
    
  563. row. In these cases you can pass the ``force_insert=True`` or
    
  564. ``force_update=True`` parameters to the :meth:`~Model.save()` method.
    
  565. Passing both parameters is an error: you cannot both insert *and* update at the
    
  566. same time!
    
  567. 
    
  568. It should be very rare that you'll need to use these parameters. Django will
    
  569. almost always do the right thing and trying to override that will lead to
    
  570. errors that are difficult to track down. This feature is for advanced use
    
  571. only.
    
  572. 
    
  573. Using ``update_fields`` will force an update similarly to ``force_update``.
    
  574. 
    
  575. .. _ref-models-field-updates-using-f-expressions:
    
  576. 
    
  577. Updating attributes based on existing fields
    
  578. --------------------------------------------
    
  579. 
    
  580. Sometimes you'll need to perform a simple arithmetic task on a field, such
    
  581. as incrementing or decrementing the current value. One way of achieving this is
    
  582. doing the arithmetic in Python like::
    
  583. 
    
  584.     >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
    
  585.     >>> product.number_sold += 1
    
  586.     >>> product.save()
    
  587. 
    
  588. If the old ``number_sold`` value retrieved from the database was 10, then
    
  589. the value of 11 will be written back to the database.
    
  590. 
    
  591. The process can be made robust, :ref:`avoiding a race condition
    
  592. <avoiding-race-conditions-using-f>`, as well as slightly faster by expressing
    
  593. the update relative to the original field value, rather than as an explicit
    
  594. assignment of a new value. Django provides :class:`F expressions
    
  595. <django.db.models.F>` for performing this kind of relative update. Using
    
  596. :class:`F expressions <django.db.models.F>`, the previous example is expressed
    
  597. as::
    
  598. 
    
  599.     >>> from django.db.models import F
    
  600.     >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
    
  601.     >>> product.number_sold = F('number_sold') + 1
    
  602.     >>> product.save()
    
  603. 
    
  604. For more details, see the documentation on :class:`F expressions
    
  605. <django.db.models.F>` and their :ref:`use in update queries
    
  606. <topics-db-queries-update>`.
    
  607. 
    
  608. .. _ref-models-update-fields:
    
  609. 
    
  610. Specifying which fields to save
    
  611. -------------------------------
    
  612. 
    
  613. If ``save()`` is passed a list of field names in keyword argument
    
  614. ``update_fields``, only the fields named in that list will be updated.
    
  615. This may be desirable if you want to update just one or a few fields on
    
  616. an object. There will be a slight performance benefit from preventing
    
  617. all of the model fields from being updated in the database. For example::
    
  618. 
    
  619.     product.name = 'Name changed again'
    
  620.     product.save(update_fields=['name'])
    
  621. 
    
  622. The ``update_fields`` argument can be any iterable containing strings. An
    
  623. empty ``update_fields`` iterable will skip the save. A value of ``None`` will
    
  624. perform an update on all fields.
    
  625. 
    
  626. Specifying ``update_fields`` will force an update.
    
  627. 
    
  628. When saving a model fetched through deferred model loading
    
  629. (:meth:`~django.db.models.query.QuerySet.only()` or
    
  630. :meth:`~django.db.models.query.QuerySet.defer()`) only the fields loaded
    
  631. from the DB will get updated. In effect there is an automatic
    
  632. ``update_fields`` in this case. If you assign or change any deferred field
    
  633. value, the field will be added to the updated fields.
    
  634. 
    
  635. .. admonition:: ``Field.pre_save()`` and ``update_fields``
    
  636. 
    
  637.     If ``update_fields`` is passed in, only the
    
  638.     :meth:`~django.db.models.Field.pre_save` methods of the ``update_fields``
    
  639.     are called. For example, this means that date/time fields with
    
  640.     ``auto_now=True`` will not be updated unless they are included in the
    
  641.     ``update_fields``.
    
  642. 
    
  643. Deleting objects
    
  644. ================
    
  645. 
    
  646. .. method:: Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False)
    
  647. 
    
  648. Issues an SQL ``DELETE`` for the object. This only deletes the object in the
    
  649. database; the Python instance will still exist and will still have data in
    
  650. its fields, except for the primary key set to ``None``. This method returns the
    
  651. number of objects deleted and a dictionary with the number of deletions per
    
  652. object type.
    
  653. 
    
  654. For more details, including how to delete objects in bulk, see
    
  655. :ref:`topics-db-queries-delete`.
    
  656. 
    
  657. If you want customized deletion behavior, you can override the ``delete()``
    
  658. method. See :ref:`overriding-model-methods` for more details.
    
  659. 
    
  660. Sometimes with :ref:`multi-table inheritance <multi-table-inheritance>` you may
    
  661. want to delete only a child model's data. Specifying ``keep_parents=True`` will
    
  662. keep the parent model's data.
    
  663. 
    
  664. Pickling objects
    
  665. ================
    
  666. 
    
  667. When you :mod:`pickle` a model, its current state is pickled. When you unpickle
    
  668. it, it'll contain the model instance at the moment it was pickled, rather than
    
  669. the data that's currently in the database.
    
  670. 
    
  671. .. admonition:: You can't share pickles between versions
    
  672. 
    
  673.     Pickles of models are only valid for the version of Django that
    
  674.     was used to generate them. If you generate a pickle using Django
    
  675.     version N, there is no guarantee that pickle will be readable with
    
  676.     Django version N+1. Pickles should not be used as part of a long-term
    
  677.     archival strategy.
    
  678. 
    
  679.     Since pickle compatibility errors can be difficult to diagnose, such as
    
  680.     silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
    
  681.     unpickle a model in a Django version that is different than the one in
    
  682.     which it was pickled.
    
  683. 
    
  684. .. _model-instance-methods:
    
  685. 
    
  686. Other model instance methods
    
  687. ============================
    
  688. 
    
  689. A few object methods have special purposes.
    
  690. 
    
  691. ``__str__()``
    
  692. -------------
    
  693. 
    
  694. .. method:: Model.__str__()
    
  695. 
    
  696. The ``__str__()`` method is called whenever you call ``str()`` on an object.
    
  697. Django uses ``str(obj)`` in a number of places. Most notably, to display an
    
  698. object in the Django admin site and as the value inserted into a template when
    
  699. it displays an object. Thus, you should always return a nice, human-readable
    
  700. representation of the model from the ``__str__()`` method.
    
  701. 
    
  702. For example::
    
  703. 
    
  704.     from django.db import models
    
  705. 
    
  706.     class Person(models.Model):
    
  707.         first_name = models.CharField(max_length=50)
    
  708.         last_name = models.CharField(max_length=50)
    
  709. 
    
  710.         def __str__(self):
    
  711.             return '%s %s' % (self.first_name, self.last_name)
    
  712. 
    
  713. ``__eq__()``
    
  714. ------------
    
  715. 
    
  716. .. method:: Model.__eq__()
    
  717. 
    
  718. The equality method is defined such that instances with the same primary
    
  719. key value and the same concrete class are considered equal, except that
    
  720. instances with a primary key value of ``None`` aren't equal to anything except
    
  721. themselves. For proxy models, concrete class is defined as the model's first
    
  722. non-proxy parent; for all other models it's simply the model's class.
    
  723. 
    
  724. For example::
    
  725. 
    
  726.     from django.db import models
    
  727. 
    
  728.     class MyModel(models.Model):
    
  729.         id = models.AutoField(primary_key=True)
    
  730. 
    
  731.     class MyProxyModel(MyModel):
    
  732.         class Meta:
    
  733.             proxy = True
    
  734. 
    
  735.     class MultitableInherited(MyModel):
    
  736.         pass
    
  737. 
    
  738.     # Primary keys compared
    
  739.     MyModel(id=1) == MyModel(id=1)
    
  740.     MyModel(id=1) != MyModel(id=2)
    
  741.     # Primary keys are None
    
  742.     MyModel(id=None) != MyModel(id=None)
    
  743.     # Same instance
    
  744.     instance = MyModel(id=None)
    
  745.     instance == instance
    
  746.     # Proxy model
    
  747.     MyModel(id=1) == MyProxyModel(id=1)
    
  748.     # Multi-table inheritance
    
  749.     MyModel(id=1) != MultitableInherited(id=1)
    
  750. 
    
  751. ``__hash__()``
    
  752. --------------
    
  753. 
    
  754. .. method:: Model.__hash__()
    
  755. 
    
  756. The ``__hash__()`` method is based on the instance's primary key value. It
    
  757. is effectively ``hash(obj.pk)``. If the instance doesn't have a primary key
    
  758. value then a ``TypeError`` will be raised (otherwise the ``__hash__()``
    
  759. method would return different values before and after the instance is
    
  760. saved, but changing the :meth:`~object.__hash__` value of an instance is
    
  761. forbidden in Python.
    
  762. 
    
  763. ``get_absolute_url()``
    
  764. ----------------------
    
  765. 
    
  766. .. method:: Model.get_absolute_url()
    
  767. 
    
  768. Define a ``get_absolute_url()`` method to tell Django how to calculate the
    
  769. canonical URL for an object. To callers, this method should appear to return a
    
  770. string that can be used to refer to the object over HTTP.
    
  771. 
    
  772. For example::
    
  773. 
    
  774.     def get_absolute_url(self):
    
  775.         return "/people/%i/" % self.id
    
  776. 
    
  777. While this code is correct and simple, it may not be the most portable way to
    
  778. to write this kind of method. The :func:`~django.urls.reverse` function is
    
  779. usually the best approach.
    
  780. 
    
  781. For example::
    
  782. 
    
  783.     def get_absolute_url(self):
    
  784.         from django.urls import reverse
    
  785.         return reverse('people-detail', kwargs={'pk' : self.pk})
    
  786. 
    
  787. One place Django uses ``get_absolute_url()`` is in the admin app. If an object
    
  788. defines this method, the object-editing page will have a "View on site" link
    
  789. that will jump you directly to the object's public view, as given by
    
  790. ``get_absolute_url()``.
    
  791. 
    
  792. Similarly, a couple of other bits of Django, such as the :doc:`syndication feed
    
  793. framework </ref/contrib/syndication>`, use ``get_absolute_url()`` when it is
    
  794. defined. If it makes sense for your model's instances to each have a unique
    
  795. URL, you should define ``get_absolute_url()``.
    
  796. 
    
  797. .. warning::
    
  798. 
    
  799.     You should avoid building the URL from unvalidated user input, in order to
    
  800.     reduce possibilities of link or redirect poisoning::
    
  801. 
    
  802.         def get_absolute_url(self):
    
  803.             return '/%s/' % self.name
    
  804. 
    
  805.     If ``self.name`` is ``'/example.com'`` this returns ``'//example.com/'``
    
  806.     which, in turn, is a valid schema relative URL but not the expected
    
  807.     ``'/%2Fexample.com/'``.
    
  808. 
    
  809. 
    
  810. It's good practice to use ``get_absolute_url()`` in templates, instead of
    
  811. hard-coding your objects' URLs. For example, this template code is bad:
    
  812. 
    
  813. .. code-block:: html+django
    
  814. 
    
  815.     <!-- BAD template code. Avoid! -->
    
  816.     <a href="/people/{{ object.id }}/">{{ object.name }}</a>
    
  817. 
    
  818. This template code is much better:
    
  819. 
    
  820. .. code-block:: html+django
    
  821. 
    
  822.     <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
    
  823. 
    
  824. The logic here is that if you change the URL structure of your objects, even
    
  825. for something small like correcting a spelling error, you don't want to have to
    
  826. track down every place that the URL might be created. Specify it once, in
    
  827. ``get_absolute_url()`` and have all your other code call that one place.
    
  828. 
    
  829. .. note::
    
  830.     The string you return from ``get_absolute_url()`` **must** contain only
    
  831.     ASCII characters (required by the URI specification, :rfc:`2396#section-2`)
    
  832.     and be URL-encoded, if necessary.
    
  833. 
    
  834.     Code and templates calling ``get_absolute_url()`` should be able to use the
    
  835.     result directly without any further processing. You may wish to use the
    
  836.     ``django.utils.encoding.iri_to_uri()`` function to help with this if you
    
  837.     are using strings containing characters outside the ASCII range.
    
  838. 
    
  839. Extra instance methods
    
  840. ======================
    
  841. 
    
  842. In addition to :meth:`~Model.save()`, :meth:`~Model.delete()`, a model object
    
  843. might have some of the following methods:
    
  844. 
    
  845. .. method:: Model.get_FOO_display()
    
  846. 
    
  847. For every field that has :attr:`~django.db.models.Field.choices` set, the
    
  848. object will have a ``get_FOO_display()`` method, where ``FOO`` is the name of
    
  849. the field. This method returns the "human-readable" value of the field.
    
  850. 
    
  851. For example::
    
  852. 
    
  853.     from django.db import models
    
  854. 
    
  855.     class Person(models.Model):
    
  856.         SHIRT_SIZES = (
    
  857.             ('S', 'Small'),
    
  858.             ('M', 'Medium'),
    
  859.             ('L', 'Large'),
    
  860.         )
    
  861.         name = models.CharField(max_length=60)
    
  862.         shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
    
  863. 
    
  864. ::
    
  865. 
    
  866.     >>> p = Person(name="Fred Flintstone", shirt_size="L")
    
  867.     >>> p.save()
    
  868.     >>> p.shirt_size
    
  869.     'L'
    
  870.     >>> p.get_shirt_size_display()
    
  871.     'Large'
    
  872. 
    
  873. .. method:: Model.get_next_by_FOO(**kwargs)
    
  874. .. method:: Model.get_previous_by_FOO(**kwargs)
    
  875. 
    
  876. For every :class:`~django.db.models.DateField` and
    
  877. :class:`~django.db.models.DateTimeField` that does not have :attr:`null=True
    
  878. <django.db.models.Field.null>`, the object will have ``get_next_by_FOO()`` and
    
  879. ``get_previous_by_FOO()`` methods, where ``FOO`` is the name of the field. This
    
  880. returns the next and previous object with respect to the date field, raising
    
  881. a :exc:`~django.db.models.Model.DoesNotExist` exception when appropriate.
    
  882. 
    
  883. Both of these methods will perform their queries using the default
    
  884. manager for the model. If you need to emulate filtering used by a
    
  885. custom manager, or want to perform one-off custom filtering, both
    
  886. methods also accept optional keyword arguments, which should be in the
    
  887. format described in :ref:`Field lookups <field-lookups>`.
    
  888. 
    
  889. Note that in the case of identical date values, these methods will use the
    
  890. primary key as a tie-breaker. This guarantees that no records are skipped or
    
  891. duplicated. That also means you cannot use those methods on unsaved objects.
    
  892. 
    
  893. .. admonition:: Overriding extra instance methods
    
  894. 
    
  895.     In most cases overriding or inheriting ``get_FOO_display()``,
    
  896.     ``get_next_by_FOO()``, and ``get_previous_by_FOO()`` should work as
    
  897.     expected. Since they are added by the metaclass however, it is not
    
  898.     practical to account for all possible inheritance structures. In more
    
  899.     complex cases you should override ``Field.contribute_to_class()`` to set
    
  900.     the methods you need.
    
  901. 
    
  902. Other attributes
    
  903. ================
    
  904. 
    
  905. ``_state``
    
  906. ----------
    
  907. 
    
  908. .. attribute:: Model._state
    
  909. 
    
  910.     The ``_state`` attribute refers to a ``ModelState`` object that tracks
    
  911.     the lifecycle of the model instance.
    
  912. 
    
  913.     The ``ModelState`` object has two attributes: ``adding``, a flag which is
    
  914.     ``True`` if the model has not been saved to the database yet, and ``db``,
    
  915.     a string referring to the database alias the instance was loaded from or
    
  916.     saved to.
    
  917. 
    
  918.     Newly instantiated instances have ``adding=True`` and ``db=None``,
    
  919.     since they are yet to be saved. Instances fetched from a ``QuerySet``
    
  920.     will have ``adding=False`` and ``db`` set to the alias of the associated
    
  921.     database.