PageRenderTime 38ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/docs/ref/models/instances.txt

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