instances.txt 34 KB

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