instances.txt 22 KB

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