instances.txt 29 KB

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