instances.txt 38 KB

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