PageRenderTime 75ms CodeModel.GetById 65ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

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