instances.txt 29 KB

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