instances.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. .. _validating-objects:
  22. Validating objects
  23. ==================
  24. .. versionadded:: 1.2
  25. There are three steps in validating a model, and all three are called by a
  26. model's ``full_clean()`` method. Most of the time, this method will be called
  27. automatically by a ``ModelForm``. (See the :ref:`ModelForm documentation
  28. <topics-forms-modelforms>` for more information.) You should only need to call
  29. ``full_clean()`` if you plan to handle validation errors yourself.
  30. .. method:: Model.full_clean(exclude=None)
  31. This method calls ``Model.clean_fields()``, ``Model.clean()``, and
  32. ``Model.validate_unique()``, in that order and raises a ``ValidationError``
  33. that has a ``message_dict`` attribute containing errors from all three stages.
  34. The optional ``exclude`` argument can be used to provide a list of field names
  35. that can be excluded from validation and cleaning. ``ModelForm`` uses this
  36. argument to exclude fields that aren't present on your form from being
  37. validated since any errors raised could not be corrected by the user.
  38. Note that ``full_clean()`` will NOT be called automatically when you call
  39. your model's ``save()`` method. You'll need to call it manually if you want
  40. to run model validation outside of a ``ModelForm``. (This is for backwards
  41. compatibility.)
  42. Example::
  43. try:
  44. article.full_validate()
  45. except ValidationError, e:
  46. # Do something based on the errors contained in e.error_dict.
  47. # Display them to a user, or handle them programatically.
  48. The first step ``full_clean()`` performs is to clean each individual field.
  49. .. method:: Model.clean_fields(exclude=None)
  50. This method will validate all fields on your model. The optional ``exclude``
  51. argument lets you provide a list of field names to exclude from validation. It
  52. will raise a ``ValidationError`` if any fields fail validation.
  53. The second step ``full_clean()`` performs is to call ``Model.clean()``.
  54. This method should be overridden to perform custom validation on your model.
  55. .. method:: Model.clean()
  56. This method should be used to provide custom model validation, and to modify
  57. attributes on your model if desired. For instance, you could use it to
  58. automatically provide a value for a field, or to do validation that requires
  59. access to more than a single field::
  60. def clean(self):
  61. from django.core.exceptions import ValidationError
  62. # Don't allow draft entries to have a pub_date.
  63. if self.status == 'draft' and self.pub_date is not None:
  64. raise ValidationError('Draft entries may not have a publication date.')
  65. # Set the pub_date for published items if it hasn't been set already.
  66. if self.status == 'published' and self.pub_date is None:
  67. self.pub_date = datetime.datetime.now()
  68. Any ``ValidationError`` raised by ``Model.clean()`` will be stored under a
  69. special key that is used for errors that are tied to the entire model instead
  70. of to a specific field. You can access these errors with ``NON_FIELD_ERRORS``::
  71. from django.core.validators import ValidationError, NON_FIELD_ERRORS
  72. try:
  73. article.full_clean():
  74. except ValidationError, e:
  75. non_field_errors = e.message_dict[NON_FIELD_ERRORS]
  76. Finally, ``full_clean()`` will check any unique constraints on your model.
  77. .. method:: Model.validate_unique(exclude=None)
  78. This method is similar to ``clean_fields``, but validates all uniqueness
  79. constraints on your model instead of individual field values. The optional
  80. ``exclude`` argument allows you to provide a list of field names to exclude
  81. from validation. It will raise a ``ValidationError`` if any fields fail
  82. validation.
  83. Note that if you provide an ``exclude`` argument to ``validate_unique``, any
  84. ``unique_together`` constraint that contains one of the fields you provided
  85. will not be checked.
  86. Saving objects
  87. ==============
  88. To save an object back to the database, call ``save()``:
  89. .. method:: Model.save([force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS])
  90. .. versionadded:: 1.0
  91. The ``force_insert`` and ``force_update`` arguments were added.
  92. .. versionadded:: 1.2
  93. The ``using`` argument was added.
  94. If you want customized saving behavior, you can override this
  95. ``save()`` method. See :ref:`overriding-model-methods` for more
  96. details.
  97. The model save process also has some subtleties; see the sections
  98. below.
  99. Auto-incrementing primary keys
  100. ------------------------------
  101. If a model has an ``AutoField`` -- an auto-incrementing primary key -- then
  102. that auto-incremented value will be calculated and saved as an attribute on
  103. your object the first time you call ``save()``::
  104. >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
  105. >>> b2.id # Returns None, because b doesn't have an ID yet.
  106. >>> b2.save()
  107. >>> b2.id # Returns the ID of your new object.
  108. There's no way to tell what the value of an ID will be before you call
  109. ``save()``, because that value is calculated by your database, not by Django.
  110. (For convenience, each model has an ``AutoField`` named ``id`` by default
  111. unless you explicitly specify ``primary_key=True`` on a field. See the
  112. documentation for ``AutoField`` for more details.
  113. The ``pk`` property
  114. ~~~~~~~~~~~~~~~~~~~
  115. .. versionadded:: 1.0
  116. .. attribute:: Model.pk
  117. Regardless of whether you define a primary key field yourself, or let Django
  118. supply one for you, each model will have a property called ``pk``. It behaves
  119. like a normal attribute on the model, but is actually an alias for whichever
  120. attribute is the primary key field for the model. You can read and set this
  121. value, just as you would for any other attribute, and it will update the
  122. correct field in the model.
  123. Explicitly specifying auto-primary-key values
  124. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  125. If a model has an ``AutoField`` but you want to define a new object's ID
  126. explicitly when saving, just define it explicitly before saving, rather than
  127. relying on the auto-assignment of the ID::
  128. >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
  129. >>> b3.id # Returns 3.
  130. >>> b3.save()
  131. >>> b3.id # Returns 3.
  132. If you assign auto-primary-key values manually, make sure not to use an
  133. already-existing primary-key value! If you create a new object with an explicit
  134. primary-key value that already exists in the database, Django will assume you're
  135. changing the existing record rather than creating a new one.
  136. Given the above ``'Cheddar Talk'`` blog example, this example would override the
  137. previous record in the database::
  138. b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
  139. b4.save() # Overrides the previous blog with ID=3!
  140. See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this
  141. happens.
  142. Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
  143. objects, when you're confident you won't have primary-key collision.
  144. What happens when you save?
  145. ---------------------------
  146. When you save an object, Django performs the following steps:
  147. 1. **Emit a pre-save signal.** The :ref:`signal <ref-signals>`
  148. :attr:`django.db.models.signals.pre_save` is sent, allowing any
  149. functions listening for that signal to take some customized
  150. action.
  151. 2. **Pre-process the data.** Each field on the object is asked to
  152. perform any automated data modification that the field may need
  153. to perform.
  154. Most fields do *no* pre-processing -- the field data is kept as-is.
  155. Pre-processing is only used on fields that have special behavior.
  156. For example, if your model has a ``DateField`` with ``auto_now=True``,
  157. the pre-save phase will alter the data in the object to ensure that
  158. the date field contains the current date stamp. (Our documentation
  159. doesn't yet include a list of all the fields with this "special
  160. behavior.")
  161. 3. **Prepare the data for the database.** Each field is asked to provide
  162. its current value in a data type that can be written to the database.
  163. Most fields require *no* data preparation. Simple data types, such as
  164. integers and strings, are 'ready to write' as a Python object. However,
  165. more complex data types often require some modification.
  166. For example, ``DateFields`` use a Python ``datetime`` object to store
  167. data. Databases don't store ``datetime`` objects, so the field value
  168. must be converted into an ISO-compliant date string for insertion
  169. into the database.
  170. 4. **Insert the data into the database.** The pre-processed, prepared
  171. data is then composed into an SQL statement for insertion into the
  172. database.
  173. 5. **Emit a post-save signal.** The signal
  174. :attr:`django.db.models.signals.post_save` is sent, allowing
  175. any functions listening for that signal to take some customized
  176. action.
  177. How Django knows to UPDATE vs. INSERT
  178. -------------------------------------
  179. You may have noticed Django database objects use the same ``save()`` method
  180. for creating and changing objects. Django abstracts the need to use ``INSERT``
  181. or ``UPDATE`` SQL statements. Specifically, when you call ``save()``, Django
  182. follows this algorithm:
  183. * If the object's primary key attribute is set to a value that evaluates to
  184. ``True`` (i.e., a value other than ``None`` or the empty string), Django
  185. executes a ``SELECT`` query to determine whether a record with the given
  186. primary key already exists.
  187. * If the record with the given primary key does already exist, Django
  188. executes an ``UPDATE`` query.
  189. * If the object's primary key attribute is *not* set, or if it's set but a
  190. record doesn't exist, Django executes an ``INSERT``.
  191. The one gotcha here is that you should be careful not to specify a primary-key
  192. value explicitly when saving new objects, if you cannot guarantee the
  193. primary-key value is unused. For more on this nuance, see `Explicitly specifying
  194. auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below.
  195. .. _ref-models-force-insert:
  196. Forcing an INSERT or UPDATE
  197. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  198. .. versionadded:: 1.0
  199. In some rare circumstances, it's necessary to be able to force the ``save()``
  200. method to perform an SQL ``INSERT`` and not fall back to doing an ``UPDATE``.
  201. Or vice-versa: update, if possible, but not insert a new row. In these cases
  202. you can pass the ``force_insert=True`` or ``force_update=True`` parameters to
  203. the ``save()`` method. Passing both parameters is an error, since you cannot
  204. both insert *and* update at the same time.
  205. It should be very rare that you'll need to use these parameters. Django will
  206. almost always do the right thing and trying to override that will lead to
  207. errors that are difficult to track down. This feature is for advanced use
  208. only.
  209. Updating attributes based on existing fields
  210. --------------------------------------------
  211. Sometimes you'll need to perform a simple arithmetic task on a field, such
  212. as incrementing or decrementing the current value. The obvious way to
  213. achieve this is to do something like::
  214. >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
  215. >>> product.number_sold += 1
  216. >>> product.save()
  217. If the old ``number_sold`` value retrieved from the database was 10, then
  218. the value of 11 will be written back to the database.
  219. This can be optimized slightly by expressing the update relative to the
  220. original field value, rather than as an explicit assignment of a new value.
  221. Django provides :ref:`F() expressions <query-expressions>` as a way of
  222. performing this kind of relative update. Using ``F()`` expressions, the
  223. previous example would be expressed as::
  224. >>> from django.db.models import F
  225. >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
  226. >>> product.number_sold = F('number_sold') + 1
  227. >>> product.save()
  228. This approach doesn't use the initial value from the database. Instead, it
  229. makes the database do the update based on whatever value is current at the
  230. time that the save() is executed.
  231. Once the object has been saved, you must reload the object in order to access
  232. the actual value that was applied to the updated field::
  233. >>> product = Products.objects.get(pk=product.pk)
  234. >>> print product.number_sold
  235. 42
  236. For more details, see the documentation on :ref:`F() expressions
  237. <query-expressions>` and their :ref:`use in update queries
  238. <topics-db-queries-update>`.
  239. Deleting objects
  240. ================
  241. .. method:: Model.delete([using=DEFAULT_DB_ALIAS])
  242. .. versionadded:: 1.2
  243. The ``using`` argument was added.
  244. Issues a SQL ``DELETE`` for the object. This only deletes the object
  245. in the database; the Python instance will still be around, and will
  246. still have data in its fields.
  247. For more details, including how to delete objects in bulk, see
  248. :ref:`topics-db-queries-delete`.
  249. If you want customized deletion behavior, you can override this
  250. ``delete()`` method. See :ref:`overriding-model-methods` for more
  251. details.
  252. .. _model-instance-methods:
  253. Other model instance methods
  254. ============================
  255. A few object methods have special purposes.
  256. ``__str__``
  257. -----------
  258. .. method:: Model.__str__()
  259. ``__str__()`` is a Python "magic method" that defines what should be returned
  260. if you call ``str()`` on the object. Django uses ``str(obj)`` (or the related
  261. function, ``unicode(obj)`` -- see below) in a number of places, most notably
  262. as the value displayed to render an object in the Django admin site and as the
  263. value inserted into a template when it displays an object. Thus, you should
  264. always return a nice, human-readable string for the object's ``__str__``.
  265. Although this isn't required, it's strongly encouraged (see the description of
  266. ``__unicode__``, below, before putting ``__str__`` methods everywhere).
  267. For example::
  268. class Person(models.Model):
  269. first_name = models.CharField(max_length=50)
  270. last_name = models.CharField(max_length=50)
  271. def __str__(self):
  272. # Note use of django.utils.encoding.smart_str() here because
  273. # first_name and last_name will be unicode strings.
  274. return smart_str('%s %s' % (self.first_name, self.last_name))
  275. ``__unicode__``
  276. ---------------
  277. .. method:: Model.__unicode__()
  278. The ``__unicode__()`` method is called whenever you call ``unicode()`` on an
  279. object. Since Django's database backends will return Unicode strings in your
  280. model's attributes, you would normally want to write a ``__unicode__()``
  281. method for your model. The example in the previous section could be written
  282. more simply as::
  283. class Person(models.Model):
  284. first_name = models.CharField(max_length=50)
  285. last_name = models.CharField(max_length=50)
  286. def __unicode__(self):
  287. return u'%s %s' % (self.first_name, self.last_name)
  288. If you define a ``__unicode__()`` method on your model and not a ``__str__()``
  289. method, Django will automatically provide you with a ``__str__()`` that calls
  290. ``__unicode__()`` and then converts the result correctly to a UTF-8 encoded
  291. string object. This is recommended development practice: define only
  292. ``__unicode__()`` and let Django take care of the conversion to string objects
  293. when required.
  294. ``get_absolute_url``
  295. --------------------
  296. .. method:: Model.get_absolute_url()
  297. Define a ``get_absolute_url()`` method to tell Django how to calculate the
  298. URL for an object. For example::
  299. def get_absolute_url(self):
  300. return "/people/%i/" % self.id
  301. Django uses this in its admin interface. If an object defines
  302. ``get_absolute_url()``, the object-editing page will have a "View on site"
  303. link that will jump you directly to the object's public view, according to
  304. ``get_absolute_url()``.
  305. Also, a couple of other bits of Django, such as the :ref:`syndication feed
  306. framework <ref-contrib-syndication>`, use ``get_absolute_url()`` as a
  307. convenience to reward people who've defined the method.
  308. It's good practice to use ``get_absolute_url()`` in templates, instead of
  309. hard-coding your objects' URLs. For example, this template code is bad::
  310. <a href="/people/{{ object.id }}/">{{ object.name }}</a>
  311. But this template code is good::
  312. <a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
  313. .. note::
  314. The string you return from ``get_absolute_url()`` must contain only ASCII
  315. characters (required by the URI spec, `RFC 2396`_) that have been
  316. URL-encoded, if necessary. Code and templates using ``get_absolute_url()``
  317. should be able to use the result directly without needing to do any
  318. further processing. You may wish to use the
  319. ``django.utils.encoding.iri_to_uri()`` function to help with this if you
  320. are using unicode strings a lot.
  321. .. _RFC 2396: http://www.ietf.org/rfc/rfc2396.txt
  322. The ``permalink`` decorator
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. The problem with the way we wrote ``get_absolute_url()`` above is that it
  325. slightly violates the DRY principle: the URL for this object is defined both
  326. in the URLconf file and in the model.
  327. You can further decouple your models from the URLconf using the ``permalink``
  328. decorator:
  329. .. function:: permalink()
  330. This decorator is passed the view function, a list of positional parameters and
  331. (optionally) a dictionary of named parameters. Django then works out the correct
  332. full URL path using the URLconf, substituting the parameters you have given into
  333. the URL. For example, if your URLconf contained a line such as::
  334. (r'^people/(\d+)/$', 'people.views.details'),
  335. ...your model could have a ``get_absolute_url`` method that looked like this::
  336. from django.db import models
  337. @models.permalink
  338. def get_absolute_url(self):
  339. return ('people.views.details', [str(self.id)])
  340. Similarly, if you had a URLconf entry that looked like::
  341. (r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)
  342. ...you could reference this using ``permalink()`` as follows::
  343. @models.permalink
  344. def get_absolute_url(self):
  345. return ('archive_view', (), {
  346. 'year': self.created.year,
  347. 'month': self.created.month,
  348. 'day': self.created.day})
  349. Notice that we specify an empty sequence for the second parameter in this case,
  350. because we only want to pass keyword parameters, not positional ones.
  351. In this way, you're tying the model's absolute URL to the view that is used
  352. to display it, without repeating the URL information anywhere. You can still
  353. use the ``get_absolute_url`` method in templates, as before.
  354. In some cases, such as the use of generic views or the re-use of
  355. custom views for multiple models, specifying the view function may
  356. confuse the reverse URL matcher (because multiple patterns point to
  357. the same view).
  358. For that problem, Django has **named URL patterns**. Using a named
  359. URL pattern, it's possible to give a name to a pattern, and then
  360. reference the name rather than the view function. A named URL
  361. pattern is defined by replacing the pattern tuple by a call to
  362. the ``url`` function)::
  363. from django.conf.urls.defaults import *
  364. url(r'^people/(\d+)/$',
  365. 'django.views.generic.list_detail.object_detail',
  366. name='people_view'),
  367. ...and then using that name to perform the reverse URL resolution instead
  368. of the view name::
  369. from django.db.models import permalink
  370. def get_absolute_url(self):
  371. return ('people_view', [str(self.id)])
  372. get_absolute_url = permalink(get_absolute_url)
  373. More details on named URL patterns are in the :ref:`URL dispatch documentation
  374. <topics-http-urls>`.
  375. Extra instance methods
  376. ======================
  377. In addition to ``save()``, ``delete()``, a model object might get any or all
  378. of the following methods:
  379. .. method:: Model.get_FOO_display()
  380. For every field that has ``choices`` set, the object will have a
  381. ``get_FOO_display()`` method, where ``FOO`` is the name of the field. This
  382. method returns the "human-readable" value of the field. For example, in the
  383. following model::
  384. GENDER_CHOICES = (
  385. ('M', 'Male'),
  386. ('F', 'Female'),
  387. )
  388. class Person(models.Model):
  389. name = models.CharField(max_length=20)
  390. gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
  391. ...each ``Person`` instance will have a ``get_gender_display()`` method. Example::
  392. >>> p = Person(name='John', gender='M')
  393. >>> p.save()
  394. >>> p.gender
  395. 'M'
  396. >>> p.get_gender_display()
  397. 'Male'
  398. .. method:: Model.get_next_by_FOO(\**kwargs)
  399. .. method:: Model.get_previous_by_FOO(\**kwargs)
  400. For every ``DateField`` and ``DateTimeField`` that does not have ``null=True``,
  401. the object will have ``get_next_by_FOO()`` and ``get_previous_by_FOO()``
  402. methods, where ``FOO`` is the name of the field. This returns the next and
  403. previous object with respect to the date field, raising the appropriate
  404. ``DoesNotExist`` exception when appropriate.
  405. Both methods accept optional keyword arguments, which should be in the format
  406. described in :ref:`Field lookups <field-lookups>`.
  407. Note that in the case of identical date values, these methods will use the ID
  408. as a fallback check. This guarantees that no records are skipped or duplicated.