instances.txt 33 KB

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