instances.txt 24 KB

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