2008-08-24 06:25:40 +08:00
|
|
|
========================
|
|
|
|
Model instance reference
|
|
|
|
========================
|
|
|
|
|
|
|
|
.. currentmodule:: django.db.models
|
2009-03-24 19:46:18 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
This document describes the details of the ``Model`` API. It builds on the
|
2010-08-20 03:27:44 +08:00
|
|
|
material presented in the :doc:`model </topics/db/models>` and :doc:`database
|
|
|
|
query </topics/db/queries>` guides, so you'll probably want to read and
|
2008-10-06 16:28:18 +08:00
|
|
|
understand those documents before reading this one.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2021-07-23 14:48:16 +08:00
|
|
|
Throughout this reference we'll use the :ref:`example blog models
|
2010-08-20 03:27:44 +08:00
|
|
|
<queryset-model-example>` presented in the :doc:`database query guide
|
|
|
|
</topics/db/queries>`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Creating objects
|
|
|
|
================
|
|
|
|
|
2019-06-17 22:54:55 +08:00
|
|
|
To create a new instance of a model, instantiate it like any other Python
|
Fixed #10389, #10501, #10502, #10540, #10562, #10563, #10564, #10565, #10568, #10569, #10614, #10617, #10619 -- Fixed several typos as well as a couple minor issues in the docs, patches from timo, nih, bthomas, rduffield, UloPe, and sebleier@gmail.com.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10242 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-03-31 15:01:01 +08:00
|
|
|
class:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. class:: Model(**kwargs)
|
|
|
|
|
2019-06-17 22:54:55 +08:00
|
|
|
The keyword arguments are the names of the fields you've defined on your model.
|
|
|
|
Note that instantiating a model in no way touches your database; for that, you
|
|
|
|
need to :meth:`~Model.save()`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-07-02 06:04:16 +08:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
You may be tempted to customize the model by overriding the ``__init__``
|
|
|
|
method. If you do so, however, take care not to change the calling
|
|
|
|
signature as any change may prevent the model instance from being saved.
|
|
|
|
Rather than overriding ``__init__``, try using one of these approaches:
|
|
|
|
|
2018-11-16 02:54:28 +08:00
|
|
|
#. Add a classmethod on the model class::
|
2012-07-02 06:04:16 +08:00
|
|
|
|
2013-05-18 18:12:26 +08:00
|
|
|
from django.db import models
|
|
|
|
|
2012-07-02 06:04:16 +08:00
|
|
|
class Book(models.Model):
|
|
|
|
title = models.CharField(max_length=100)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def create(cls, title):
|
|
|
|
book = cls(title=title)
|
|
|
|
# do something with the book
|
|
|
|
return book
|
|
|
|
|
|
|
|
book = Book.create("Pride and Prejudice")
|
|
|
|
|
2018-11-16 02:54:28 +08:00
|
|
|
#. Add a method on a custom manager (usually preferred)::
|
2012-07-02 06:04:16 +08:00
|
|
|
|
|
|
|
class BookManager(models.Manager):
|
2012-08-31 10:19:11 +08:00
|
|
|
def create_book(self, title):
|
2012-07-02 06:04:16 +08:00
|
|
|
book = self.create(title=title)
|
|
|
|
# do something with the book
|
|
|
|
return book
|
|
|
|
|
|
|
|
class Book(models.Model):
|
|
|
|
title = models.CharField(max_length=100)
|
|
|
|
|
|
|
|
objects = BookManager()
|
|
|
|
|
|
|
|
book = Book.objects.create_book("Pride and Prejudice")
|
|
|
|
|
2014-06-06 20:35:40 +08:00
|
|
|
Customizing model loading
|
|
|
|
-------------------------
|
|
|
|
|
|
|
|
.. classmethod:: Model.from_db(db, field_names, values)
|
|
|
|
|
|
|
|
The ``from_db()`` method can be used to customize model instance creation
|
|
|
|
when loading from the database.
|
|
|
|
|
|
|
|
The ``db`` argument contains the database alias for the database the model
|
|
|
|
is loaded from, ``field_names`` contains the names of all loaded fields, and
|
|
|
|
``values`` contains the loaded values for each field in ``field_names``. The
|
2016-02-02 17:33:09 +08:00
|
|
|
``field_names`` are in the same order as the ``values``. If all of the model's
|
|
|
|
fields are present, then ``values`` are guaranteed to be in the order
|
|
|
|
``__init__()`` expects them. That is, the instance can be created by
|
|
|
|
``cls(*values)``. If any fields are deferred, they won't appear in
|
|
|
|
``field_names``. In that case, assign a value of ``django.db.models.DEFERRED``
|
|
|
|
to each of the missing fields.
|
2014-06-06 20:35:40 +08:00
|
|
|
|
|
|
|
In addition to creating the new model, the ``from_db()`` method must set the
|
2020-07-06 12:30:00 +08:00
|
|
|
``adding`` and ``db`` flags in the new instance's :attr:`~Model._state` attribute.
|
2014-06-06 20:35:40 +08:00
|
|
|
|
2014-07-03 01:21:34 +08:00
|
|
|
Below is an example showing how to record the initial values of fields that
|
|
|
|
are loaded from the database::
|
2014-06-06 20:35:40 +08:00
|
|
|
|
2016-02-02 17:33:09 +08:00
|
|
|
from django.db.models import DEFERRED
|
|
|
|
|
2014-06-06 20:35:40 +08:00
|
|
|
@classmethod
|
|
|
|
def from_db(cls, db, field_names, values):
|
2016-02-02 17:33:09 +08:00
|
|
|
# Default implementation of from_db() (subject to change and could
|
|
|
|
# be replaced with super()).
|
|
|
|
if len(values) != len(cls._meta.concrete_fields):
|
|
|
|
values = list(values)
|
|
|
|
values.reverse()
|
|
|
|
values = [
|
|
|
|
values.pop() if f.attname in field_names else DEFERRED
|
|
|
|
for f in cls._meta.concrete_fields
|
|
|
|
]
|
2017-06-02 21:17:15 +08:00
|
|
|
instance = cls(*values)
|
2014-06-06 20:35:40 +08:00
|
|
|
instance._state.adding = False
|
|
|
|
instance._state.db = db
|
|
|
|
# customization to store the original field values on the instance
|
2015-07-03 07:00:56 +08:00
|
|
|
instance._loaded_values = dict(zip(field_names, values))
|
2014-06-06 20:35:40 +08:00
|
|
|
return instance
|
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
|
|
|
# Check how the current values differ from ._loaded_values. For example,
|
|
|
|
# prevent changing the creator_id of the model. (This example doesn't
|
|
|
|
# support cases where 'creator_id' is deferred).
|
|
|
|
if not self._state.adding and (
|
|
|
|
self.creator_id != self._loaded_values['creator_id']):
|
|
|
|
raise ValueError("Updating the value of creator isn't allowed")
|
2017-01-22 14:57:14 +08:00
|
|
|
super().save(*args, **kwargs)
|
2014-06-06 20:35:40 +08:00
|
|
|
|
|
|
|
The example above shows a full ``from_db()`` implementation to clarify how that
|
2020-05-01 20:37:21 +08:00
|
|
|
is done. In this case it would be possible to use a ``super()`` call in the
|
|
|
|
``from_db()`` method.
|
2014-06-06 20:35:40 +08:00
|
|
|
|
2014-07-05 14:03:52 +08:00
|
|
|
Refreshing objects from database
|
|
|
|
================================
|
|
|
|
|
2016-06-22 01:46:22 +08:00
|
|
|
If you delete a field from a model instance, accessing it again reloads the
|
|
|
|
value from the database::
|
|
|
|
|
|
|
|
>>> obj = MyModel.objects.first()
|
|
|
|
>>> del obj.field
|
|
|
|
>>> obj.field # Loads the field from the database
|
|
|
|
|
2016-05-17 02:49:03 +08:00
|
|
|
.. method:: Model.refresh_from_db(using=None, fields=None)
|
2014-07-05 14:03:52 +08:00
|
|
|
|
|
|
|
If you need to reload a model's values from the database, you can use the
|
|
|
|
``refresh_from_db()`` method. When this method is called without arguments the
|
|
|
|
following is done:
|
|
|
|
|
2018-11-16 02:54:28 +08:00
|
|
|
#. All non-deferred fields of the model are updated to the values currently
|
2014-07-05 14:03:52 +08:00
|
|
|
present in the database.
|
2018-11-16 02:54:28 +08:00
|
|
|
#. Any cached relations are cleared from the reloaded instance.
|
2014-07-05 14:03:52 +08:00
|
|
|
|
2016-08-13 06:49:21 +08:00
|
|
|
Only fields of the model are reloaded from the database. Other
|
|
|
|
database-dependent values such as annotations aren't reloaded. Any
|
|
|
|
:func:`@cached_property <django.utils.functional.cached_property>` attributes
|
|
|
|
aren't cleared either.
|
2014-07-05 14:03:52 +08:00
|
|
|
|
|
|
|
The reloading happens from the database the instance was loaded from, or from
|
|
|
|
the default database if the instance wasn't loaded from the database. The
|
|
|
|
``using`` argument can be used to force the database used for reloading.
|
|
|
|
|
|
|
|
It is possible to force the set of fields to be loaded by using the ``fields``
|
|
|
|
argument.
|
|
|
|
|
|
|
|
For example, to test that an ``update()`` call resulted in the expected
|
|
|
|
update, you could write a test similar to this::
|
|
|
|
|
|
|
|
def test_update_result(self):
|
|
|
|
obj = MyModel.objects.create(val=1)
|
|
|
|
MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
|
|
|
|
# At this point obj.val is still 1, but the value in the database
|
|
|
|
# was updated to 2. The object's updated value needs to be reloaded
|
|
|
|
# from the database.
|
|
|
|
obj.refresh_from_db()
|
|
|
|
self.assertEqual(obj.val, 2)
|
|
|
|
|
|
|
|
Note that when deferred fields are accessed, the loading of the deferred
|
|
|
|
field's value happens through this method. Thus it is possible to customize
|
|
|
|
the way deferred loading happens. The example below shows how one can reload
|
|
|
|
all of the instance's fields when a deferred field is reloaded::
|
|
|
|
|
|
|
|
class ExampleModel(models.Model):
|
|
|
|
def refresh_from_db(self, using=None, fields=None, **kwargs):
|
|
|
|
# fields contains the name of the deferred field to be
|
|
|
|
# loaded.
|
|
|
|
if fields is not None:
|
|
|
|
fields = set(fields)
|
|
|
|
deferred_fields = self.get_deferred_fields()
|
|
|
|
# If any deferred field is going to be loaded
|
|
|
|
if fields.intersection(deferred_fields):
|
|
|
|
# then load all of them
|
|
|
|
fields = fields.union(deferred_fields)
|
2017-01-22 14:57:14 +08:00
|
|
|
super().refresh_from_db(using, fields, **kwargs)
|
2014-07-05 14:03:52 +08:00
|
|
|
|
|
|
|
.. method:: Model.get_deferred_fields()
|
|
|
|
|
|
|
|
A helper method that returns a set containing the attribute names of all those
|
|
|
|
fields that are currently deferred for this model.
|
|
|
|
|
2010-01-05 14:18:41 +08:00
|
|
|
.. _validating-objects:
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
Validating objects
|
|
|
|
==================
|
|
|
|
|
2010-05-09 13:47:35 +08:00
|
|
|
There are three steps involved in validating a model:
|
|
|
|
|
2012-11-05 20:14:40 +08:00
|
|
|
1. Validate the model fields - :meth:`Model.clean_fields()`
|
|
|
|
2. Validate the model as a whole - :meth:`Model.clean()`
|
|
|
|
3. Validate the field uniqueness - :meth:`Model.validate_unique()`
|
2010-05-09 13:47:35 +08:00
|
|
|
|
2011-05-31 17:42:19 +08:00
|
|
|
All three steps are performed when you call a model's
|
2011-08-28 10:05:20 +08:00
|
|
|
:meth:`~Model.full_clean()` method.
|
2010-05-09 13:47:35 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
When you use a :class:`~django.forms.ModelForm`, the call to
|
|
|
|
:meth:`~django.forms.Form.is_valid()` will perform these validation steps for
|
|
|
|
all the fields that are included on the form. See the :doc:`ModelForm
|
|
|
|
documentation </topics/forms/modelforms>` for more information. You should only
|
|
|
|
need to call a model's :meth:`~Model.full_clean()` method if you plan to handle
|
2010-05-09 13:47:35 +08:00
|
|
|
validation errors yourself, or if you have excluded fields from the
|
2011-08-28 10:05:20 +08:00
|
|
|
:class:`~django.forms.ModelForm` that require validation.
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-06-06 02:55:05 +08:00
|
|
|
.. method:: Model.full_clean(exclude=None, validate_unique=True)
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
This method calls :meth:`Model.clean_fields()`, :meth:`Model.clean()`, and
|
2014-03-24 23:42:56 +08:00
|
|
|
:meth:`Model.validate_unique()` (if ``validate_unique`` is ``True``), in that
|
2013-06-06 02:55:05 +08:00
|
|
|
order and raises a :exc:`~django.core.exceptions.ValidationError` that has a
|
|
|
|
``message_dict`` attribute containing errors from all three stages.
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2010-01-12 10:29:45 +08:00
|
|
|
The optional ``exclude`` argument can be used to provide a list of field names
|
2011-08-28 10:05:20 +08:00
|
|
|
that can be excluded from validation and cleaning.
|
|
|
|
:class:`~django.forms.ModelForm` uses this argument to exclude fields that
|
|
|
|
aren't present on your form from being validated since any errors raised could
|
|
|
|
not be corrected by the user.
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
Note that ``full_clean()`` will *not* be called automatically when you call
|
2013-08-22 03:38:07 +08:00
|
|
|
your model's :meth:`~Model.save()` method. You'll need to call it manually
|
|
|
|
when you want to run one-step model validation for your own manually created
|
|
|
|
models. For example::
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-05-18 18:12:26 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2010-01-12 10:29:45 +08:00
|
|
|
try:
|
2010-01-12 22:04:04 +08:00
|
|
|
article.full_clean()
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2010-10-21 05:08:06 +08:00
|
|
|
# Do something based on the errors contained in e.message_dict.
|
2013-07-28 09:45:25 +08:00
|
|
|
# Display them to a user, or handle them programmatically.
|
2012-11-05 20:14:40 +08:00
|
|
|
pass
|
2010-01-12 10:29:45 +08:00
|
|
|
|
|
|
|
The first step ``full_clean()`` performs is to clean each individual field.
|
|
|
|
|
|
|
|
.. method:: Model.clean_fields(exclude=None)
|
|
|
|
|
|
|
|
This method will validate all fields on your model. The optional ``exclude``
|
|
|
|
argument lets you provide a list of field names to exclude from validation. It
|
2011-08-28 10:05:20 +08:00
|
|
|
will raise a :exc:`~django.core.exceptions.ValidationError` if any fields fail
|
|
|
|
validation.
|
2010-01-12 10:29:45 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
The second step ``full_clean()`` performs is to call :meth:`Model.clean()`.
|
2010-01-12 10:29:45 +08:00
|
|
|
This method should be overridden to perform custom validation on your model.
|
|
|
|
|
|
|
|
.. method:: Model.clean()
|
|
|
|
|
|
|
|
This method should be used to provide custom model validation, and to modify
|
|
|
|
attributes on your model if desired. For instance, you could use it to
|
|
|
|
automatically provide a value for a field, or to do validation that requires
|
|
|
|
access to more than a single field::
|
|
|
|
|
2013-08-05 03:40:16 +08:00
|
|
|
import datetime
|
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from django.db import models
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2013-08-05 03:40:16 +08:00
|
|
|
|
|
|
|
class Article(models.Model):
|
|
|
|
...
|
|
|
|
def clean(self):
|
|
|
|
# Don't allow draft entries to have a pub_date.
|
|
|
|
if self.status == 'draft' and self.pub_date is not None:
|
2015-08-03 13:30:26 +08:00
|
|
|
raise ValidationError(_('Draft entries may not have a publication date.'))
|
2013-08-05 03:40:16 +08:00
|
|
|
# Set the pub_date for published items if it hasn't been set already.
|
|
|
|
if self.status == 'published' and self.pub_date is None:
|
|
|
|
self.pub_date = datetime.date.today()
|
2010-01-12 10:29:45 +08:00
|
|
|
|
2014-04-19 03:00:26 +08:00
|
|
|
Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()``
|
|
|
|
method is not invoked when you call your model's :meth:`~Model.save()` method.
|
|
|
|
|
2014-11-19 01:58:43 +08:00
|
|
|
In the above example, the :exc:`~django.core.exceptions.ValidationError`
|
|
|
|
exception raised by ``Model.clean()`` was instantiated with a string, so it
|
|
|
|
will be stored in a special error dictionary key,
|
|
|
|
:data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors
|
2014-02-04 02:31:27 +08:00
|
|
|
that are tied to the entire model instead of to a specific field::
|
2010-01-12 10:29:45 +08:00
|
|
|
|
2018-05-13 01:37:42 +08:00
|
|
|
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
|
2010-01-12 10:29:45 +08:00
|
|
|
try:
|
2010-06-18 02:29:27 +08:00
|
|
|
article.full_clean()
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2010-01-12 10:29:45 +08:00
|
|
|
non_field_errors = e.message_dict[NON_FIELD_ERRORS]
|
|
|
|
|
2014-11-19 01:58:43 +08:00
|
|
|
To assign exceptions to a specific field, instantiate the
|
|
|
|
:exc:`~django.core.exceptions.ValidationError` with a dictionary, where the
|
|
|
|
keys are the field names. We could update the previous example to assign the
|
|
|
|
error to the ``pub_date`` field::
|
|
|
|
|
|
|
|
class Article(models.Model):
|
|
|
|
...
|
|
|
|
def clean(self):
|
|
|
|
# Don't allow draft entries to have a pub_date.
|
|
|
|
if self.status == 'draft' and self.pub_date is not None:
|
2015-08-03 13:30:26 +08:00
|
|
|
raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')})
|
2014-11-19 01:58:43 +08:00
|
|
|
...
|
|
|
|
|
2015-08-03 13:30:26 +08:00
|
|
|
If you detect errors in multiple fields during ``Model.clean()``, you can also
|
|
|
|
pass a dictionary mapping field names to errors::
|
|
|
|
|
|
|
|
raise ValidationError({
|
|
|
|
'title': ValidationError(_('Missing title.'), code='required'),
|
|
|
|
'pub_date': ValidationError(_('Invalid date.'), code='invalid'),
|
|
|
|
})
|
|
|
|
|
2010-01-12 10:29:45 +08:00
|
|
|
Finally, ``full_clean()`` will check any unique constraints on your model.
|
|
|
|
|
2017-04-23 18:55:07 +08:00
|
|
|
.. admonition:: How to raise field-specific validation errors if those fields don't appear in a ``ModelForm``
|
|
|
|
|
|
|
|
You can't raise validation errors in ``Model.clean()`` for fields that
|
|
|
|
don't appear in a model form (a form may limit its fields using
|
|
|
|
``Meta.fields`` or ``Meta.exclude``). Doing so will raise a ``ValueError``
|
|
|
|
because the validation error won't be able to be associated with the
|
|
|
|
excluded field.
|
|
|
|
|
|
|
|
To work around this dilemma, instead override :meth:`Model.clean_fields()
|
|
|
|
<django.db.models.Model.clean_fields>` as it receives the list of fields
|
|
|
|
that are excluded from validation. For example::
|
|
|
|
|
|
|
|
class Article(models.Model):
|
|
|
|
...
|
|
|
|
def clean_fields(self, exclude=None):
|
|
|
|
super().clean_fields(exclude=exclude)
|
|
|
|
if self.status == 'draft' and self.pub_date is not None:
|
|
|
|
if exclude and 'status' in exclude:
|
|
|
|
raise ValidationError(
|
|
|
|
_('Draft entries may not have a publication date.')
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise ValidationError({
|
|
|
|
'status': _(
|
|
|
|
'Set status to draft if there is not a '
|
|
|
|
'publication date.'
|
|
|
|
),
|
|
|
|
})
|
|
|
|
|
2010-01-12 10:29:45 +08:00
|
|
|
.. method:: Model.validate_unique(exclude=None)
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
This method is similar to :meth:`~Model.clean_fields`, but validates all
|
|
|
|
uniqueness constraints on your model instead of individual field values. The
|
|
|
|
optional ``exclude`` argument allows you to provide a list of field names to
|
|
|
|
exclude from validation. It will raise a
|
|
|
|
:exc:`~django.core.exceptions.ValidationError` if any fields fail validation.
|
2010-01-12 10:29:45 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
Note that if you provide an ``exclude`` argument to ``validate_unique()``, any
|
|
|
|
:attr:`~django.db.models.Options.unique_together` constraint involving one of
|
|
|
|
the fields you provided will not be checked.
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Saving objects
|
|
|
|
==============
|
|
|
|
|
|
|
|
To save an object back to the database, call ``save()``:
|
|
|
|
|
2015-07-27 20:35:21 +08:00
|
|
|
.. method:: Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2021-07-23 16:43:19 +08:00
|
|
|
For details on using the ``force_insert`` and ``force_update`` arguments, see
|
|
|
|
:ref:`ref-models-force-insert`. Details about the ``update_fields`` argument
|
|
|
|
can be found in the :ref:`ref-models-update-fields` section.
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
If you want customized saving behavior, you can override this ``save()``
|
|
|
|
method. See :ref:`overriding-model-methods` for more details.
|
2008-09-04 04:55:04 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
The model save process also has some subtleties; see the sections below.
|
2008-08-29 09:44:15 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Auto-incrementing primary keys
|
|
|
|
------------------------------
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
If a model has an :class:`~django.db.models.AutoField` — an auto-incrementing
|
|
|
|
primary key — then that auto-incremented value will be calculated and saved as
|
|
|
|
an attribute on your object the first time you call ``save()``::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
|
2019-04-16 14:26:11 +08:00
|
|
|
>>> b2.id # Returns None, because b2 doesn't have an ID yet.
|
2008-08-24 06:25:40 +08:00
|
|
|
>>> b2.save()
|
|
|
|
>>> b2.id # Returns the ID of your new object.
|
|
|
|
|
|
|
|
There's no way to tell what the value of an ID will be before you call
|
|
|
|
``save()``, because that value is calculated by your database, not by Django.
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
For convenience, each model has an :class:`~django.db.models.AutoField` named
|
|
|
|
``id`` by default unless you explicitly specify ``primary_key=True`` on a field
|
|
|
|
in your model. See the documentation for :class:`~django.db.models.AutoField`
|
|
|
|
for more details.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
The ``pk`` property
|
|
|
|
~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
.. attribute:: Model.pk
|
|
|
|
|
|
|
|
Regardless of whether you define a primary key field yourself, or let Django
|
|
|
|
supply one for you, each model will have a property called ``pk``. It behaves
|
|
|
|
like a normal attribute on the model, but is actually an alias for whichever
|
|
|
|
attribute is the primary key field for the model. You can read and set this
|
|
|
|
value, just as you would for any other attribute, and it will update the
|
|
|
|
correct field in the model.
|
|
|
|
|
|
|
|
Explicitly specifying auto-primary-key values
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
If a model has an :class:`~django.db.models.AutoField` but you want to define a
|
2019-06-17 22:54:55 +08:00
|
|
|
new object's ID explicitly when saving, define it explicitly before saving,
|
|
|
|
rather than relying on the auto-assignment of the ID::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
>>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
|
|
|
|
>>> b3.id # Returns 3.
|
|
|
|
>>> b3.save()
|
|
|
|
>>> b3.id # Returns 3.
|
|
|
|
|
|
|
|
If you assign auto-primary-key values manually, make sure not to use an
|
|
|
|
already-existing primary-key value! If you create a new object with an explicit
|
|
|
|
primary-key value that already exists in the database, Django will assume you're
|
|
|
|
changing the existing record rather than creating a new one.
|
|
|
|
|
|
|
|
Given the above ``'Cheddar Talk'`` blog example, this example would override the
|
|
|
|
previous record in the database::
|
|
|
|
|
|
|
|
b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
|
|
|
|
b4.save() # Overrides the previous blog with ID=3!
|
|
|
|
|
|
|
|
See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this
|
|
|
|
happens.
|
|
|
|
|
|
|
|
Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
|
|
|
|
objects, when you're confident you won't have primary-key collision.
|
|
|
|
|
2017-06-18 11:17:15 +08:00
|
|
|
If you're using PostgreSQL, the sequence associated with the primary key might
|
|
|
|
need to be updated; see :ref:`manually-specified-autoincrement-pk`.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
What happens when you save?
|
|
|
|
---------------------------
|
|
|
|
|
|
|
|
When you save an object, Django performs the following steps:
|
|
|
|
|
2016-12-17 23:24:08 +08:00
|
|
|
#. **Emit a pre-save signal.** The :data:`~django.db.models.signals.pre_save`
|
|
|
|
signal is sent, allowing any functions listening for that signal to do
|
|
|
|
something.
|
|
|
|
|
|
|
|
#. **Preprocess the data.** Each field's
|
|
|
|
:meth:`~django.db.models.Field.pre_save` method is called to perform any
|
|
|
|
automated data modification that's needed. For example, the date/time fields
|
|
|
|
override ``pre_save()`` to implement
|
|
|
|
:attr:`~django.db.models.DateField.auto_now_add` and
|
|
|
|
:attr:`~django.db.models.DateField.auto_now`.
|
|
|
|
|
|
|
|
#. **Prepare the data for the database.** Each field's
|
|
|
|
:meth:`~django.db.models.Field.get_db_prep_save` method is asked to provide
|
2011-10-14 08:12:01 +08:00
|
|
|
its current value in a data type that can be written to the database.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2016-12-17 23:24:08 +08:00
|
|
|
Most fields don't require data preparation. Simple data types, such as
|
|
|
|
integers and strings, are 'ready to write' as a Python object. However, more
|
|
|
|
complex data types often require some modification.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
For example, :class:`~django.db.models.DateField` fields use a Python
|
|
|
|
``datetime`` object to store data. Databases don't store ``datetime``
|
|
|
|
objects, so the field value must be converted into an ISO-compliant date
|
|
|
|
string for insertion into the database.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2016-12-17 23:24:08 +08:00
|
|
|
#. **Insert the data into the database.** The preprocessed, prepared data is
|
|
|
|
composed into an SQL statement for insertion into the database.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2016-12-17 23:24:08 +08:00
|
|
|
#. **Emit a post-save signal.** The :data:`~django.db.models.signals.post_save`
|
|
|
|
signal is sent, allowing any functions listening for that signal to do
|
|
|
|
something.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
How Django knows to UPDATE vs. INSERT
|
|
|
|
-------------------------------------
|
|
|
|
|
|
|
|
You may have noticed Django database objects use the same ``save()`` method
|
|
|
|
for creating and changing objects. Django abstracts the need to use ``INSERT``
|
2019-12-12 12:09:38 +08:00
|
|
|
or ``UPDATE`` SQL statements. Specifically, when you call ``save()`` and the
|
|
|
|
object's primary key attribute does **not** define a
|
|
|
|
:attr:`~django.db.models.Field.default`, Django follows this algorithm:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* If the object's primary key attribute is set to a value that evaluates to
|
|
|
|
``True`` (i.e., a value other than ``None`` or the empty string), Django
|
2012-11-29 18:10:31 +08:00
|
|
|
executes an ``UPDATE``.
|
|
|
|
* If the object's primary key attribute is *not* set or if the ``UPDATE``
|
2019-05-27 20:47:15 +08:00
|
|
|
didn't update anything (e.g. if primary key is set to a value that doesn't
|
|
|
|
exist in the database), Django executes an ``INSERT``.
|
2012-11-29 18:10:31 +08:00
|
|
|
|
2019-12-12 12:09:38 +08:00
|
|
|
If the object's primary key attribute defines a
|
|
|
|
:attr:`~django.db.models.Field.default` then Django executes an ``UPDATE`` if
|
|
|
|
it is an existing model instance and primary key is set to a value that exists
|
|
|
|
in the database. Otherwise, Django executes an ``INSERT``.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
The one gotcha here is that you should be careful not to specify a primary-key
|
|
|
|
value explicitly when saving new objects, if you cannot guarantee the
|
|
|
|
primary-key value is unused. For more on this nuance, see `Explicitly specifying
|
|
|
|
auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below.
|
|
|
|
|
2014-03-24 23:42:56 +08:00
|
|
|
In Django 1.5 and earlier, Django did a ``SELECT`` when the primary key
|
|
|
|
attribute was set. If the ``SELECT`` found a row, then Django did an ``UPDATE``,
|
|
|
|
otherwise it did an ``INSERT``. The old algorithm results in one more query in
|
|
|
|
the ``UPDATE`` case. There are some rare cases where the database doesn't
|
|
|
|
report that a row was updated even if the database contains a row for the
|
|
|
|
object's primary key value. An example is the PostgreSQL ``ON UPDATE`` trigger
|
|
|
|
which returns ``NULL``. In such cases it is possible to revert to the old
|
|
|
|
algorithm by setting the :attr:`~django.db.models.Options.select_on_save`
|
|
|
|
option to ``True``.
|
2013-08-30 14:41:07 +08:00
|
|
|
|
2008-08-29 01:18:05 +08:00
|
|
|
.. _ref-models-force-insert:
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Forcing an INSERT or UPDATE
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
In some rare circumstances, it's necessary to be able to force the
|
|
|
|
:meth:`~Model.save()` method to perform an SQL ``INSERT`` and not fall back to
|
|
|
|
doing an ``UPDATE``. Or vice-versa: update, if possible, but not insert a new
|
|
|
|
row. In these cases you can pass the ``force_insert=True`` or
|
|
|
|
``force_update=True`` parameters to the :meth:`~Model.save()` method.
|
2019-06-17 22:54:55 +08:00
|
|
|
Passing both parameters is an error: you cannot both insert *and* update at the
|
|
|
|
same time!
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
It should be very rare that you'll need to use these parameters. Django will
|
|
|
|
almost always do the right thing and trying to override that will lead to
|
|
|
|
errors that are difficult to track down. This feature is for advanced use
|
|
|
|
only.
|
|
|
|
|
2012-05-12 15:24:20 +08:00
|
|
|
Using ``update_fields`` will force an update similarly to ``force_update``.
|
|
|
|
|
2013-09-07 01:57:25 +08:00
|
|
|
.. _ref-models-field-updates-using-f-expressions:
|
|
|
|
|
2009-07-24 21:38:36 +08:00
|
|
|
Updating attributes based on existing fields
|
|
|
|
--------------------------------------------
|
|
|
|
|
|
|
|
Sometimes you'll need to perform a simple arithmetic task on a field, such
|
2020-05-01 20:37:21 +08:00
|
|
|
as incrementing or decrementing the current value. One way of achieving this is
|
|
|
|
doing the arithmetic in Python like::
|
2009-07-24 21:38:36 +08:00
|
|
|
|
|
|
|
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
|
|
|
|
>>> product.number_sold += 1
|
|
|
|
>>> product.save()
|
|
|
|
|
|
|
|
If the old ``number_sold`` value retrieved from the database was 10, then
|
|
|
|
the value of 11 will be written back to the database.
|
|
|
|
|
2013-09-07 01:57:25 +08:00
|
|
|
The process can be made robust, :ref:`avoiding a race condition
|
|
|
|
<avoiding-race-conditions-using-f>`, as well as slightly faster by expressing
|
|
|
|
the update relative to the original field value, rather than as an explicit
|
|
|
|
assignment of a new value. Django provides :class:`F expressions
|
|
|
|
<django.db.models.F>` for performing this kind of relative update. Using
|
|
|
|
:class:`F expressions <django.db.models.F>`, the previous example is expressed
|
|
|
|
as::
|
2009-07-24 21:38:36 +08:00
|
|
|
|
|
|
|
>>> from django.db.models import F
|
|
|
|
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
|
|
|
|
>>> product.number_sold = F('number_sold') + 1
|
|
|
|
>>> product.save()
|
|
|
|
|
2013-09-07 01:57:25 +08:00
|
|
|
For more details, see the documentation on :class:`F expressions
|
|
|
|
<django.db.models.F>` and their :ref:`use in update queries
|
2009-07-24 21:38:36 +08:00
|
|
|
<topics-db-queries-update>`.
|
|
|
|
|
2021-07-23 16:43:19 +08:00
|
|
|
.. _ref-models-update-fields:
|
|
|
|
|
2012-05-12 15:24:20 +08:00
|
|
|
Specifying which fields to save
|
|
|
|
-------------------------------
|
|
|
|
|
|
|
|
If ``save()`` is passed a list of field names in keyword argument
|
|
|
|
``update_fields``, only the fields named in that list will be updated.
|
|
|
|
This may be desirable if you want to update just one or a few fields on
|
|
|
|
an object. There will be a slight performance benefit from preventing
|
2012-11-28 10:57:50 +08:00
|
|
|
all of the model fields from being updated in the database. For example::
|
2012-05-12 15:24:20 +08:00
|
|
|
|
|
|
|
product.name = 'Name changed again'
|
|
|
|
product.save(update_fields=['name'])
|
|
|
|
|
|
|
|
The ``update_fields`` argument can be any iterable containing strings. An
|
2020-12-15 14:19:00 +08:00
|
|
|
empty ``update_fields`` iterable will skip the save. A value of ``None`` will
|
2012-05-12 15:24:20 +08:00
|
|
|
perform an update on all fields.
|
|
|
|
|
|
|
|
Specifying ``update_fields`` will force an update.
|
|
|
|
|
2012-08-13 03:17:54 +08:00
|
|
|
When saving a model fetched through deferred model loading
|
2012-09-30 07:43:47 +08:00
|
|
|
(:meth:`~django.db.models.query.QuerySet.only()` or
|
|
|
|
:meth:`~django.db.models.query.QuerySet.defer()`) only the fields loaded
|
|
|
|
from the DB will get updated. In effect there is an automatic
|
|
|
|
``update_fields`` in this case. If you assign or change any deferred field
|
|
|
|
value, the field will be added to the updated fields.
|
2012-08-13 03:17:54 +08:00
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-04 02:30:54 +08:00
|
|
|
Deleting objects
|
|
|
|
================
|
|
|
|
|
2015-07-27 20:35:21 +08:00
|
|
|
.. method:: Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False)
|
2010-01-08 08:17:33 +08:00
|
|
|
|
2013-09-06 06:23:48 +08:00
|
|
|
Issues an SQL ``DELETE`` for the object. This only deletes the object in the
|
2011-08-28 10:05:20 +08:00
|
|
|
database; the Python instance will still exist and will still have data in
|
2015-03-07 16:56:25 +08:00
|
|
|
its fields. This method returns the number of objects deleted and a dictionary
|
|
|
|
with the number of deletions per object type.
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-04 02:30:54 +08:00
|
|
|
|
2010-01-08 08:17:33 +08:00
|
|
|
For more details, including how to delete objects in bulk, see
|
|
|
|
:ref:`topics-db-queries-delete`.
|
2009-07-24 21:38:36 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
If you want customized deletion behavior, you can override the ``delete()``
|
|
|
|
method. See :ref:`overriding-model-methods` for more details.
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-04 02:30:54 +08:00
|
|
|
|
2015-02-07 07:16:26 +08:00
|
|
|
Sometimes with :ref:`multi-table inheritance <multi-table-inheritance>` you may
|
|
|
|
want to delete only a child model's data. Specifying ``keep_parents=True`` will
|
|
|
|
keep the parent model's data.
|
|
|
|
|
2014-06-06 19:10:20 +08:00
|
|
|
Pickling objects
|
|
|
|
================
|
|
|
|
|
|
|
|
When you :mod:`pickle` a model, its current state is pickled. When you unpickle
|
|
|
|
it, it'll contain the model instance at the moment it was pickled, rather than
|
|
|
|
the data that's currently in the database.
|
|
|
|
|
|
|
|
.. admonition:: You can't share pickles between versions
|
|
|
|
|
|
|
|
Pickles of models are only valid for the version of Django that
|
|
|
|
was used to generate them. If you generate a pickle using Django
|
|
|
|
version N, there is no guarantee that pickle will be readable with
|
|
|
|
Django version N+1. Pickles should not be used as part of a long-term
|
|
|
|
archival strategy.
|
|
|
|
|
|
|
|
Since pickle compatibility errors can be difficult to diagnose, such as
|
|
|
|
silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
|
|
|
|
unpickle a model in a Django version that is different than the one in
|
|
|
|
which it was pickled.
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
.. _model-instance-methods:
|
|
|
|
|
|
|
|
Other model instance methods
|
|
|
|
============================
|
|
|
|
|
|
|
|
A few object methods have special purposes.
|
|
|
|
|
2016-05-09 06:07:43 +08:00
|
|
|
``__str__()``
|
|
|
|
-------------
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
.. method:: Model.__str__()
|
|
|
|
|
2015-09-26 01:28:12 +08:00
|
|
|
The ``__str__()`` method is called whenever you call ``str()`` on an object.
|
|
|
|
Django uses ``str(obj)`` in a number of places. Most notably, to display an
|
|
|
|
object in the Django admin site and as the value inserted into a template when
|
|
|
|
it displays an object. Thus, you should always return a nice, human-readable
|
2014-02-09 19:38:13 +08:00
|
|
|
representation of the model from the ``__str__()`` method.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(max_length=50)
|
|
|
|
last_name = models.CharField(max_length=50)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return '%s %s' % (self.first_name, self.last_name)
|
|
|
|
|
2016-05-09 06:07:43 +08:00
|
|
|
``__eq__()``
|
|
|
|
------------
|
2013-08-07 14:51:32 +08:00
|
|
|
|
|
|
|
.. method:: Model.__eq__()
|
|
|
|
|
|
|
|
The equality method is defined such that instances with the same primary
|
2016-10-07 17:40:16 +08:00
|
|
|
key value and the same concrete class are considered equal, except that
|
|
|
|
instances with a primary key value of ``None`` aren't equal to anything except
|
|
|
|
themselves. For proxy models, concrete class is defined as the model's first
|
|
|
|
non-proxy parent; for all other models it's simply the model's class.
|
2013-08-07 14:51:32 +08:00
|
|
|
|
|
|
|
For example::
|
|
|
|
|
2014-05-15 06:34:59 +08:00
|
|
|
from django.db import models
|
2013-08-07 14:51:32 +08:00
|
|
|
|
|
|
|
class MyModel(models.Model):
|
|
|
|
id = models.AutoField(primary_key=True)
|
|
|
|
|
|
|
|
class MyProxyModel(MyModel):
|
|
|
|
class Meta:
|
|
|
|
proxy = True
|
|
|
|
|
|
|
|
class MultitableInherited(MyModel):
|
|
|
|
pass
|
|
|
|
|
2016-10-07 17:40:16 +08:00
|
|
|
# Primary keys compared
|
2013-08-07 14:51:32 +08:00
|
|
|
MyModel(id=1) == MyModel(id=1)
|
2016-10-07 17:40:16 +08:00
|
|
|
MyModel(id=1) != MyModel(id=2)
|
2018-08-02 00:55:53 +08:00
|
|
|
# Primary keys are None
|
2016-10-07 17:40:16 +08:00
|
|
|
MyModel(id=None) != MyModel(id=None)
|
|
|
|
# Same instance
|
|
|
|
instance = MyModel(id=None)
|
|
|
|
instance == instance
|
|
|
|
# Proxy model
|
2013-08-07 14:51:32 +08:00
|
|
|
MyModel(id=1) == MyProxyModel(id=1)
|
2016-10-07 17:40:16 +08:00
|
|
|
# Multi-table inheritance
|
2013-08-07 14:51:32 +08:00
|
|
|
MyModel(id=1) != MultitableInherited(id=1)
|
|
|
|
|
2016-05-09 06:07:43 +08:00
|
|
|
``__hash__()``
|
|
|
|
--------------
|
2013-08-14 16:05:01 +08:00
|
|
|
|
|
|
|
.. method:: Model.__hash__()
|
|
|
|
|
2016-05-09 06:07:43 +08:00
|
|
|
The ``__hash__()`` method is based on the instance's primary key value. It
|
|
|
|
is effectively ``hash(obj.pk)``. If the instance doesn't have a primary key
|
|
|
|
value then a ``TypeError`` will be raised (otherwise the ``__hash__()``
|
2013-08-14 16:05:01 +08:00
|
|
|
method would return different values before and after the instance is
|
2016-05-09 06:07:43 +08:00
|
|
|
saved, but changing the :meth:`~object.__hash__` value of an instance is
|
|
|
|
forbidden in Python.
|
2013-08-14 16:05:01 +08:00
|
|
|
|
2016-05-09 06:07:43 +08:00
|
|
|
``get_absolute_url()``
|
|
|
|
----------------------
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
.. method:: Model.get_absolute_url()
|
|
|
|
|
|
|
|
Define a ``get_absolute_url()`` method to tell Django how to calculate the
|
2011-08-28 10:05:32 +08:00
|
|
|
canonical URL for an object. To callers, this method should appear to return a
|
|
|
|
string that can be used to refer to the object over HTTP.
|
|
|
|
|
|
|
|
For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
def get_absolute_url(self):
|
|
|
|
return "/people/%i/" % self.id
|
|
|
|
|
2015-12-30 23:51:16 +08:00
|
|
|
While this code is correct and simple, it may not be the most portable way to
|
|
|
|
to write this kind of method. The :func:`~django.urls.reverse` function is
|
|
|
|
usually the best approach.
|
2012-11-20 20:15:16 +08:00
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
def get_absolute_url(self):
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.urls import reverse
|
2021-05-18 17:30:38 +08:00
|
|
|
return reverse('people-detail', kwargs={'pk' : self.pk})
|
2011-08-28 10:05:32 +08:00
|
|
|
|
|
|
|
One place Django uses ``get_absolute_url()`` is in the admin app. If an object
|
|
|
|
defines this method, the object-editing page will have a "View on site" link
|
|
|
|
that will jump you directly to the object's public view, as given by
|
2008-08-24 06:25:40 +08:00
|
|
|
``get_absolute_url()``.
|
|
|
|
|
2011-08-28 10:05:32 +08:00
|
|
|
Similarly, a couple of other bits of Django, such as the :doc:`syndication feed
|
|
|
|
framework </ref/contrib/syndication>`, use ``get_absolute_url()`` when it is
|
|
|
|
defined. If it makes sense for your model's instances to each have a unique
|
|
|
|
URL, you should define ``get_absolute_url()``.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2014-10-05 01:49:58 +08:00
|
|
|
.. warning::
|
|
|
|
|
2014-10-28 22:15:52 +08:00
|
|
|
You should avoid building the URL from unvalidated user input, in order to
|
2014-10-05 01:49:58 +08:00
|
|
|
reduce possibilities of link or redirect poisoning::
|
|
|
|
|
|
|
|
def get_absolute_url(self):
|
|
|
|
return '/%s/' % self.name
|
|
|
|
|
|
|
|
If ``self.name`` is ``'/example.com'`` this returns ``'//example.com/'``
|
|
|
|
which, in turn, is a valid schema relative URL but not the expected
|
|
|
|
``'/%2Fexample.com/'``.
|
|
|
|
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
It's good practice to use ``get_absolute_url()`` in templates, instead of
|
2012-10-08 07:11:12 +08:00
|
|
|
hard-coding your objects' URLs. For example, this template code is bad:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-08-28 10:05:32 +08:00
|
|
|
<!-- BAD template code. Avoid! -->
|
2008-08-24 06:25:40 +08:00
|
|
|
<a href="/people/{{ object.id }}/">{{ object.name }}</a>
|
|
|
|
|
2012-10-08 07:11:12 +08:00
|
|
|
This template code is much better:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
|
|
|
|
|
2011-08-28 10:05:32 +08:00
|
|
|
The logic here is that if you change the URL structure of your objects, even
|
2019-06-17 22:54:55 +08:00
|
|
|
for something small like correcting a spelling error, you don't want to have to
|
|
|
|
track down every place that the URL might be created. Specify it once, in
|
|
|
|
``get_absolute_url()`` and have all your other code call that one place.
|
2011-08-28 10:05:32 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
.. note::
|
2011-08-28 10:05:32 +08:00
|
|
|
The string you return from ``get_absolute_url()`` **must** contain only
|
2019-11-23 20:42:57 +08:00
|
|
|
ASCII characters (required by the URI specification, :rfc:`2396#section-2`)
|
|
|
|
and be URL-encoded, if necessary.
|
2011-08-28 10:05:32 +08:00
|
|
|
|
|
|
|
Code and templates calling ``get_absolute_url()`` should be able to use the
|
|
|
|
result directly without any further processing. You may wish to use the
|
2008-08-24 06:25:40 +08:00
|
|
|
``django.utils.encoding.iri_to_uri()`` function to help with this if you
|
2017-01-24 00:44:25 +08:00
|
|
|
are using strings containing characters outside the ASCII range.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
Extra instance methods
|
|
|
|
======================
|
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
In addition to :meth:`~Model.save()`, :meth:`~Model.delete()`, a model object
|
|
|
|
might have some of the following methods:
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2009-03-24 19:46:18 +08:00
|
|
|
.. method:: Model.get_FOO_display()
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
For every field that has :attr:`~django.db.models.Field.choices` set, the
|
|
|
|
object will have a ``get_FOO_display()`` method, where ``FOO`` is the name of
|
2012-06-06 17:54:26 +08:00
|
|
|
the field. This method returns the "human-readable" value of the field.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-06-06 17:54:26 +08:00
|
|
|
For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2012-11-05 01:52:37 +08:00
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
SHIRT_SIZES = (
|
2014-03-23 04:30:49 +08:00
|
|
|
('S', 'Small'),
|
|
|
|
('M', 'Medium'),
|
|
|
|
('L', 'Large'),
|
2012-11-05 01:52:37 +08:00
|
|
|
)
|
|
|
|
name = models.CharField(max_length=60)
|
|
|
|
shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
>>> p = Person(name="Fred Flintstone", shirt_size="L")
|
|
|
|
>>> p.save()
|
|
|
|
>>> p.shirt_size
|
2014-03-23 04:30:49 +08:00
|
|
|
'L'
|
2012-11-05 01:52:37 +08:00
|
|
|
>>> p.get_shirt_size_display()
|
2014-03-23 04:30:49 +08:00
|
|
|
'Large'
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2019-06-20 20:04:36 +08:00
|
|
|
.. method:: Model.get_next_by_FOO(**kwargs)
|
|
|
|
.. method:: Model.get_previous_by_FOO(**kwargs)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
For every :class:`~django.db.models.DateField` and
|
|
|
|
:class:`~django.db.models.DateTimeField` that does not have :attr:`null=True
|
|
|
|
<django.db.models.Field.null>`, the object will have ``get_next_by_FOO()`` and
|
|
|
|
``get_previous_by_FOO()`` methods, where ``FOO`` is the name of the field. This
|
|
|
|
returns the next and previous object with respect to the date field, raising
|
2015-05-08 09:30:04 +08:00
|
|
|
a :exc:`~django.db.models.Model.DoesNotExist` exception when appropriate.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2013-06-20 14:36:13 +08:00
|
|
|
Both of these methods will perform their queries using the default
|
|
|
|
manager for the model. If you need to emulate filtering used by a
|
|
|
|
custom manager, or want to perform one-off custom filtering, both
|
|
|
|
methods also accept optional keyword arguments, which should be in the
|
|
|
|
format described in :ref:`Field lookups <field-lookups>`.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2011-08-28 10:05:20 +08:00
|
|
|
Note that in the case of identical date values, these methods will use the
|
|
|
|
primary key as a tie-breaker. This guarantees that no records are skipped or
|
|
|
|
duplicated. That also means you cannot use those methods on unsaved objects.
|
2015-05-08 09:30:04 +08:00
|
|
|
|
2020-01-07 18:52:09 +08:00
|
|
|
.. admonition:: Overriding extra instance methods
|
|
|
|
|
|
|
|
In most cases overriding or inheriting ``get_FOO_display()``,
|
2020-01-18 03:26:36 +08:00
|
|
|
``get_next_by_FOO()``, and ``get_previous_by_FOO()`` should work as
|
2020-01-07 18:52:09 +08:00
|
|
|
expected. Since they are added by the metaclass however, it is not
|
|
|
|
practical to account for all possible inheritance structures. In more
|
|
|
|
complex cases you should override ``Field.contribute_to_class()`` to set
|
|
|
|
the methods you need.
|
|
|
|
|
2015-05-08 09:30:04 +08:00
|
|
|
Other attributes
|
|
|
|
================
|
|
|
|
|
2020-07-06 12:30:00 +08:00
|
|
|
``_state``
|
|
|
|
----------
|
|
|
|
|
|
|
|
.. attribute:: Model._state
|
|
|
|
|
|
|
|
The ``_state`` attribute refers to a ``ModelState`` object that tracks
|
|
|
|
the lifecycle of the model instance.
|
|
|
|
|
|
|
|
The ``ModelState`` object has two attributes: ``adding``, a flag which is
|
|
|
|
``True`` if the model has not been saved to the database yet, and ``db``,
|
|
|
|
a string referring to the database alias the instance was loaded from or
|
|
|
|
saved to.
|
|
|
|
|
|
|
|
Newly instantiated instances have ``adding=True`` and ``db=None``,
|
|
|
|
since they are yet to be saved. Instances fetched from a ``QuerySet``
|
|
|
|
will have ``adding=False`` and ``db`` set to the alias of the associated
|
|
|
|
database.
|