instances.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. .. _ref-models-instances:
  2. ========================
  3. Model instance reference
  4. ========================
  5. .. currentmodule:: django.db.models
  6. This document describes the details of the ``Model`` API. It builds on the
  7. material presented in the :ref:`model <topics-db-models>` and :ref:`database
  8. query <topics-db-queries>` guides, so you'll probably want to read and
  9. understand those documents before reading this one.
  10. Throughout this reference we'll use the :ref:`example weblog models
  11. <queryset-model-example>` presented in the :ref:`database query guide
  12. <topics-db-queries>`.
  13. Creating objects
  14. ================
  15. To create a new instance of a model, just instantiate it like any other Python
  16. class:
  17. .. class:: Model(**kwargs)
  18. The keyword arguments are simply the names of the fields you've defined on your
  19. model. Note that instantiating a model in no way touches your database; for
  20. that, you need to ``save()``.
  21. Saving objects
  22. ==============
  23. To save an object back to the database, call ``save()``:
  24. .. method:: Model.save([force_insert=False, force_update=False])
  25. Of course, there are some subtleties; see the sections below.
  26. .. versionadded:: 1.0
  27. The signature of the ``save()`` method has changed from earlier versions
  28. (``force_insert`` and ``force_update`` have been added). If you are overriding
  29. these methods, be sure to use the correct signature.
  30. Auto-incrementing primary keys
  31. ------------------------------
  32. If a model has an ``AutoField`` -- an auto-incrementing primary key -- then
  33. that auto-incremented value will be calculated and saved as an attribute on
  34. your object the first time you call ``save()``::
  35. >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
  36. >>> b2.id # Returns None, because b doesn't have an ID yet.
  37. >>> b2.save()
  38. >>> b2.id # Returns the ID of your new object.
  39. There's no way to tell what the value of an ID will be before you call
  40. ``save()``, because that value is calculated by your database, not by Django.
  41. (For convenience, each model has an ``AutoField`` named ``id`` by default
  42. unless you explicitly specify ``primary_key=True`` on a field. See the
  43. documentation for ``AutoField`` for more details.
  44. The ``pk`` property
  45. ~~~~~~~~~~~~~~~~~~~
  46. .. versionadded:: 1.0
  47. .. attribute:: Model.pk
  48. Regardless of whether you define a primary key field yourself, or let Django
  49. supply one for you, each model will have a property called ``pk``. It behaves
  50. like a normal attribute on the model, but is actually an alias for whichever
  51. attribute is the primary key field for the model. You can read and set this
  52. value, just as you would for any other attribute, and it will update the
  53. correct field in the model.
  54. Explicitly specifying auto-primary-key values
  55. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  56. If a model has an ``AutoField`` but you want to define a new object's ID
  57. explicitly when saving, just define it explicitly before saving, rather than
  58. relying on the auto-assignment of the ID::
  59. >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
  60. >>> b3.id # Returns 3.
  61. >>> b3.save()
  62. >>> b3.id # Returns 3.
  63. If you assign auto-primary-key values manually, make sure not to use an
  64. already-existing primary-key value! If you create a new object with an explicit
  65. primary-key value that already exists in the database, Django will assume you're
  66. changing the existing record rather than creating a new one.
  67. Given the above ``'Cheddar Talk'`` blog example, this example would override the
  68. previous record in the database::
  69. b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
  70. b4.save() # Overrides the previous blog with ID=3!
  71. See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this
  72. happens.
  73. Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
  74. objects, when you're confident you won't have primary-key collision.
  75. What happens when you save?
  76. ---------------------------
  77. When you save an object, Django performs the following steps:
  78. 1. **Emit a pre-save signal.** The :ref:`signal <ref-signals>`
  79. :attr:`django.db.models.signals.pre_save` is sent, allowing any
  80. functions listening for that signal to take some customized
  81. action.
  82. 2. **Pre-process the data.** Each field on the object is asked to
  83. perform any automated data modification that the field may need
  84. to perform.
  85. Most fields do *no* pre-processing -- the field data is kept as-is.
  86. Pre-processing is only used on fields that have special behavior.
  87. For example, if your model has a ``DateField`` with ``auto_now=True``,
  88. the pre-save phase will alter the data in the object to ensure that
  89. the date field contains the current date stamp. (Our documentation
  90. doesn't yet include a list of all the fields with this "special
  91. behavior.")
  92. 3. **Prepare the data for the database.** Each field is asked to provide
  93. its current value in a data type that can be written to the database.
  94. Most fields require *no* data preparation. Simple data types, such as
  95. integers and strings, are 'ready to write' as a Python object. However,
  96. more complex data types often require some modification.
  97. For example, ``DateFields`` use a Python ``datetime`` object to store
  98. data. Databases don't store ``datetime`` objects, so the field value
  99. must be converted into an ISO-compliant date string for insertion
  100. into the database.
  101. 4. **Insert the data into the database.** The pre-processed, prepared
  102. data is then composed into an SQL statement for insertion into the
  103. database.
  104. 5. **Emit a post-save signal.** The signal
  105. :attr:`django.db.models.signals.post_save` is sent, allowing
  106. any functions listening for that signal to take some customized
  107. action.
  108. How Django knows to UPDATE vs. INSERT
  109. -------------------------------------
  110. You may have noticed Django database objects use the same ``save()`` method
  111. for creating and changing objects. Django abstracts the need to use ``INSERT``
  112. or ``UPDATE`` SQL statements. Specifically, when you call ``save()``, Django
  113. follows this algorithm:
  114. * If the object's primary key attribute is set to a value that evaluates to
  115. ``True`` (i.e., a value other than ``None`` or the empty string), Django
  116. executes a ``SELECT`` query to determine whether a record with the given
  117. primary key already exists.
  118. * If the record with the given primary key does already exist, Django
  119. executes an ``UPDATE`` query.
  120. * If the object's primary key attribute is *not* set, or if it's set but a
  121. record doesn't exist, Django executes an ``INSERT``.
  122. The one gotcha here is that you should be careful not to specify a primary-key
  123. value explicitly when saving new objects, if you cannot guarantee the
  124. primary-key value is unused. For more on this nuance, see `Explicitly specifying
  125. auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below.
  126. .. _ref-models-force-insert:
  127. Forcing an INSERT or UPDATE
  128. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  129. .. versionadded:: 1.0
  130. In some rare circumstances, it's necessary to be able to force the ``save()``
  131. method to perform an SQL ``INSERT`` and not fall back to doing an ``UPDATE``.
  132. Or vice-versa: update, if possible, but not insert a new row. In these cases
  133. you can pass the ``force_insert=True`` or ``force_update=True`` parameters to
  134. the ``save()`` method. Passing both parameters is an error, since you cannot
  135. both insert *and* update at the same time.
  136. It should be very rare that you'll need to use these parameters. Django will
  137. almost always do the right thing and trying to override that will lead to
  138. errors that are difficult to track down. This feature is for advanced use
  139. only.
  140. .. _model-instance-methods:
  141. Other model instance methods
  142. ============================
  143. A few object methods have special purposes.
  144. ``__str__``
  145. -----------
  146. .. method:: Model.__str__()
  147. ``__str__()`` is a Python "magic method" that defines what should be returned
  148. if you call ``str()`` on the object. Django uses ``str(obj)`` (or the related
  149. function, ``unicode(obj)`` -- see below) in a number of places, most notably
  150. as the value displayed to render an object in the Django admin site and as the
  151. value inserted into a template when it displays an object. Thus, you should
  152. always return a nice, human-readable string for the object's ``__str__``.
  153. Although this isn't required, it's strongly encouraged (see the description of
  154. ``__unicode__``, below, before putting ``__str__`` methods everywhere).
  155. For example::
  156. class Person(models.Model):
  157. first_name = models.CharField(max_length=50)
  158. last_name = models.CharField(max_length=50)
  159. def __str__(self):
  160. # Note use of django.utils.encoding.smart_str() here because
  161. # first_name and last_name will be unicode strings.
  162. return smart_str('%s %s' % (self.first_name, self.last_name))
  163. ``__unicode__``
  164. ---------------
  165. .. method:: Model.__unicode__()
  166. The ``__unicode__()`` method is called whenever you call ``unicode()`` on an
  167. object. Since Django's database backends will return Unicode strings in your
  168. model's attributes, you would normally want to write a ``__unicode__()``
  169. method for your model. The example in the previous section could be written
  170. more simply as::
  171. class Person(models.Model):
  172. first_name = models.CharField(max_length=50)
  173. last_name = models.CharField(max_length=50)
  174. def __unicode__(self):
  175. return u'%s %s' % (self.first_name, self.last_name)
  176. If you define a ``__unicode__()`` method on your model and not a ``__str__()``
  177. method, Django will automatically provide you with a ``__str__()`` that calls
  178. ``__unicode__()`` and then converts the result correctly to a UTF-8 encoded
  179. string object. This is recommended development practice: define only
  180. ``__unicode__()`` and let Django take care of the conversion to string objects
  181. when required.
  182. ``get_absolute_url``
  183. --------------------
  184. .. method:: Model.get_absolute_url()
  185. Define a ``get_absolute_url()`` method to tell Django how to calculate the
  186. URL for an object. For example::
  187. def get_absolute_url(self):
  188. return "/people/%i/" % self.id
  189. Django uses this in its admin interface. If an object defines
  190. ``get_absolute_url()``, the object-editing page will have a "View on site"
  191. link that will jump you directly to the object's public view, according to
  192. ``get_absolute_url()``.
  193. Also, a couple of other bits of Django, such as the :ref:`syndication feed
  194. framework <ref-contrib-syndication>`, use ``get_absolute_url()`` as a
  195. convenience to reward people who've defined the method.
  196. It's good practice to use ``get_absolute_url()`` in templates, instead of
  197. hard-coding your objects' URLs. For example, this template code is bad::
  198. <a href="/people/{{ object.id }}/">{{ object.name }}</a>
  199. But this template code is good::
  200. <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
  201. .. note::
  202. The string you return from ``get_absolute_url()`` must contain only ASCII
  203. characters (required by the URI spec, `RFC 2396`_) that have been
  204. URL-encoded, if necessary. Code and templates using ``get_absolute_url()``
  205. should be able to use the result directly without needing to do any
  206. further processing. You may wish to use the
  207. ``django.utils.encoding.iri_to_uri()`` function to help with this if you
  208. are using unicode strings a lot.
  209. .. _RFC 2396: http://www.ietf.org/rfc/rfc2396.txt
  210. The ``permalink`` decorator
  211. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  212. The problem with the way we wrote ``get_absolute_url()`` above is that it
  213. slightly violates the DRY principle: the URL for this object is defined both
  214. in the URLConf file and in the model.
  215. You can further decouple your models from the URLconf using the ``permalink``
  216. decorator:
  217. .. function:: permalink()
  218. This decorator is passed the view function, a list of positional parameters and
  219. (optionally) a dictionary of named parameters. Django then works out the correct
  220. full URL path using the URLconf, substituting the parameters you have given into
  221. the URL. For example, if your URLconf contained a line such as::
  222. (r'^people/(\d+)/$', 'people.views.details'),
  223. ...your model could have a ``get_absolute_url`` method that looked like this::
  224. from django.db import models
  225. @models.permalink
  226. def get_absolute_url(self):
  227. return ('people.views.details', [str(self.id)])
  228. Similarly, if you had a URLconf entry that looked like::
  229. (r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)
  230. ...you could reference this using ``permalink()`` as follows::
  231. @models.permalink
  232. def get_absolute_url(self):
  233. return ('archive_view', (), {
  234. 'year': self.created.year,
  235. 'month': self.created.month,
  236. 'day': self.created.day})
  237. Notice that we specify an empty sequence for the second parameter in this case,
  238. because we only want to pass keyword parameters, not positional ones.
  239. In this way, you're tying the model's absolute URL to the view that is used
  240. to display it, without repeating the URL information anywhere. You can still
  241. use the ``get_absolute_url`` method in templates, as before.
  242. In some cases, such as the use of generic views or the re-use of
  243. custom views for multiple models, specifying the view function may
  244. confuse the reverse URL matcher (because multiple patterns point to
  245. the same view).
  246. For that problem, Django has **named URL patterns**. Using a named
  247. URL pattern, it's possible to give a name to a pattern, and then
  248. reference the name rather than the view function. A named URL
  249. pattern is defined by replacing the pattern tuple by a call to
  250. the ``url`` function)::
  251. from django.conf.urls.defaults import *
  252. url(r'^people/(\d+)/$',
  253. 'django.views.generic.list_detail.object_detail',
  254. name='people_view'),
  255. ...and then using that name to perform the reverse URL resolution instead
  256. of the view name::
  257. from django.db.models import permalink
  258. def get_absolute_url(self):
  259. return ('people_view', [str(self.id)])
  260. get_absolute_url = permalink(get_absolute_url)
  261. More details on named URL patterns are in the :ref:`URL dispatch documentation
  262. <topics-http-urls>`.
  263. Extra instance methods
  264. ======================
  265. In addition to ``save()``, ``delete()``, a model object might get any or all
  266. of the following methods:
  267. .. method:: Model.get_FOO_display()
  268. For every field that has ``choices`` set, the object will have a
  269. ``get_FOO_display()`` method, where ``FOO`` is the name of the field. This
  270. method returns the "human-readable" value of the field. For example, in the
  271. following model::
  272. GENDER_CHOICES = (
  273. ('M', 'Male'),
  274. ('F', 'Female'),
  275. )
  276. class Person(models.Model):
  277. name = models.CharField(max_length=20)
  278. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  279. ...each ``Person`` instance will have a ``get_gender_display()`` method. Example::
  280. >>> p = Person(name='John', gender='M')
  281. >>> p.save()
  282. >>> p.gender
  283. 'M'
  284. >>> p.get_gender_display()
  285. 'Male'
  286. .. method:: Model.get_next_by_FOO(\**kwargs)
  287. .. method:: Model.get_previous_by_FOO(\**kwargs)
  288. For every ``DateField`` and ``DateTimeField`` that does not have ``null=True``,
  289. the object will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()``
  290. methods, where ``FOO`` is the name of the field. This returns the next and
  291. previous object with respect to the date field, raising the appropriate
  292. ``DoesNotExist`` exception when appropriate.
  293. Both methods accept optional keyword arguments, which should be in the format
  294. described in :ref:`Field lookups <field-lookups>`.
  295. Note that in the case of identical date values, these methods will use the ID
  296. as a fallback check. This guarantees that no records are skipped or duplicated.