instances.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. Deleting objects
  141. ================
  142. .. method:: Model.delete()
  143. Issues a SQL ``DELETE`` for the object. This only deletes the object in the
  144. database; the Python instance will still be around, and will still have data
  145. in its fields.
  146. For more details, including how to delete objects in bulk, see
  147. :ref:`topics-db-queries-delete`.
  148. .. _model-instance-methods:
  149. Other model instance methods
  150. ============================
  151. A few object methods have special purposes.
  152. ``__str__``
  153. -----------
  154. .. method:: Model.__str__()
  155. ``__str__()`` is a Python "magic method" that defines what should be returned
  156. if you call ``str()`` on the object. Django uses ``str(obj)`` (or the related
  157. function, ``unicode(obj)`` -- see below) in a number of places, most notably
  158. as the value displayed to render an object in the Django admin site and as the
  159. value inserted into a template when it displays an object. Thus, you should
  160. always return a nice, human-readable string for the object's ``__str__``.
  161. Although this isn't required, it's strongly encouraged (see the description of
  162. ``__unicode__``, below, before putting ``__str__`` methods everywhere).
  163. For example::
  164. class Person(models.Model):
  165. first_name = models.CharField(max_length=50)
  166. last_name = models.CharField(max_length=50)
  167. def __str__(self):
  168. # Note use of django.utils.encoding.smart_str() here because
  169. # first_name and last_name will be unicode strings.
  170. return smart_str('%s %s' % (self.first_name, self.last_name))
  171. ``__unicode__``
  172. ---------------
  173. .. method:: Model.__unicode__()
  174. The ``__unicode__()`` method is called whenever you call ``unicode()`` on an
  175. object. Since Django's database backends will return Unicode strings in your
  176. model's attributes, you would normally want to write a ``__unicode__()``
  177. method for your model. The example in the previous section could be written
  178. more simply as::
  179. class Person(models.Model):
  180. first_name = models.CharField(max_length=50)
  181. last_name = models.CharField(max_length=50)
  182. def __unicode__(self):
  183. return u'%s %s' % (self.first_name, self.last_name)
  184. If you define a ``__unicode__()`` method on your model and not a ``__str__()``
  185. method, Django will automatically provide you with a ``__str__()`` that calls
  186. ``__unicode__()`` and then converts the result correctly to a UTF-8 encoded
  187. string object. This is recommended development practice: define only
  188. ``__unicode__()`` and let Django take care of the conversion to string objects
  189. when required.
  190. ``get_absolute_url``
  191. --------------------
  192. .. method:: Model.get_absolute_url()
  193. Define a ``get_absolute_url()`` method to tell Django how to calculate the
  194. URL for an object. For example::
  195. def get_absolute_url(self):
  196. return "/people/%i/" % self.id
  197. Django uses this in its admin interface. If an object defines
  198. ``get_absolute_url()``, the object-editing page will have a "View on site"
  199. link that will jump you directly to the object's public view, according to
  200. ``get_absolute_url()``.
  201. Also, a couple of other bits of Django, such as the :ref:`syndication feed
  202. framework <ref-contrib-syndication>`, use ``get_absolute_url()`` as a
  203. convenience to reward people who've defined the method.
  204. It's good practice to use ``get_absolute_url()`` in templates, instead of
  205. hard-coding your objects' URLs. For example, this template code is bad::
  206. <a href="/people/{{ object.id }}/">{{ object.name }}</a>
  207. But this template code is good::
  208. <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
  209. .. note::
  210. The string you return from ``get_absolute_url()`` must contain only ASCII
  211. characters (required by the URI spec, `RFC 2396`_) that have been
  212. URL-encoded, if necessary. Code and templates using ``get_absolute_url()``
  213. should be able to use the result directly without needing to do any
  214. further processing. You may wish to use the
  215. ``django.utils.encoding.iri_to_uri()`` function to help with this if you
  216. are using unicode strings a lot.
  217. .. _RFC 2396: http://www.ietf.org/rfc/rfc2396.txt
  218. The ``permalink`` decorator
  219. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  220. The problem with the way we wrote ``get_absolute_url()`` above is that it
  221. slightly violates the DRY principle: the URL for this object is defined both
  222. in the URLconf file and in the model.
  223. You can further decouple your models from the URLconf using the ``permalink``
  224. decorator:
  225. .. function:: permalink()
  226. This decorator is passed the view function, a list of positional parameters and
  227. (optionally) a dictionary of named parameters. Django then works out the correct
  228. full URL path using the URLconf, substituting the parameters you have given into
  229. the URL. For example, if your URLconf contained a line such as::
  230. (r'^people/(\d+)/$', 'people.views.details'),
  231. ...your model could have a ``get_absolute_url`` method that looked like this::
  232. from django.db import models
  233. @models.permalink
  234. def get_absolute_url(self):
  235. return ('people.views.details', [str(self.id)])
  236. Similarly, if you had a URLconf entry that looked like::
  237. (r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)
  238. ...you could reference this using ``permalink()`` as follows::
  239. @models.permalink
  240. def get_absolute_url(self):
  241. return ('archive_view', (), {
  242. 'year': self.created.year,
  243. 'month': self.created.month,
  244. 'day': self.created.day})
  245. Notice that we specify an empty sequence for the second parameter in this case,
  246. because we only want to pass keyword parameters, not positional ones.
  247. In this way, you're tying the model's absolute URL to the view that is used
  248. to display it, without repeating the URL information anywhere. You can still
  249. use the ``get_absolute_url`` method in templates, as before.
  250. In some cases, such as the use of generic views or the re-use of
  251. custom views for multiple models, specifying the view function may
  252. confuse the reverse URL matcher (because multiple patterns point to
  253. the same view).
  254. For that problem, Django has **named URL patterns**. Using a named
  255. URL pattern, it's possible to give a name to a pattern, and then
  256. reference the name rather than the view function. A named URL
  257. pattern is defined by replacing the pattern tuple by a call to
  258. the ``url`` function)::
  259. from django.conf.urls.defaults import *
  260. url(r'^people/(\d+)/$',
  261. 'django.views.generic.list_detail.object_detail',
  262. name='people_view'),
  263. ...and then using that name to perform the reverse URL resolution instead
  264. of the view name::
  265. from django.db.models import permalink
  266. def get_absolute_url(self):
  267. return ('people_view', [str(self.id)])
  268. get_absolute_url = permalink(get_absolute_url)
  269. More details on named URL patterns are in the :ref:`URL dispatch documentation
  270. <topics-http-urls>`.
  271. Extra instance methods
  272. ======================
  273. In addition to ``save()``, ``delete()``, a model object might get any or all
  274. of the following methods:
  275. .. method:: Model.get_FOO_display()
  276. For every field that has ``choices`` set, the object will have a
  277. ``get_FOO_display()`` method, where ``FOO`` is the name of the field. This
  278. method returns the "human-readable" value of the field. For example, in the
  279. following model::
  280. GENDER_CHOICES = (
  281. ('M', 'Male'),
  282. ('F', 'Female'),
  283. )
  284. class Person(models.Model):
  285. name = models.CharField(max_length=20)
  286. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  287. ...each ``Person`` instance will have a ``get_gender_display()`` method. Example::
  288. >>> p = Person(name='John', gender='M')
  289. >>> p.save()
  290. >>> p.gender
  291. 'M'
  292. >>> p.get_gender_display()
  293. 'Male'
  294. .. method:: Model.get_next_by_FOO(\**kwargs)
  295. .. method:: Model.get_previous_by_FOO(\**kwargs)
  296. For every ``DateField`` and ``DateTimeField`` that does not have ``null=True``,
  297. the object will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()``
  298. methods, where ``FOO`` is the name of the field. This returns the next and
  299. previous object with respect to the date field, raising the appropriate
  300. ``DoesNotExist`` exception when appropriate.
  301. Both methods accept optional keyword arguments, which should be in the format
  302. described in :ref:`Field lookups <field-lookups>`.
  303. Note that in the case of identical date values, these methods will use the ID
  304. as a fallback check. This guarantees that no records are skipped or duplicated.