| 1 |
======================== |
| 2 |
Model instance reference |
| 3 |
======================== |
| 4 |
|
| 5 |
.. currentmodule:: django.db.models |
| 6 |
|
| 7 |
This document describes the details of the ``Model`` API. It builds on the |
| 8 |
material presented in the :doc:`model </topics/db/models>` and :doc:`database |
| 9 |
query </topics/db/queries>` guides, so you'll probably want to read and |
| 10 |
understand those documents before reading this one. |
| 11 |
|
| 12 |
Throughout this reference we'll use the :ref:`example blog models |
| 13 |
<queryset-model-example>` presented in the :doc:`database query guide |
| 14 |
</topics/db/queries>`. |
| 15 |
|
| 16 |
Creating objects |
| 17 |
================ |
| 18 |
|
| 19 |
To create a new instance of a model, instantiate it like any other Python |
| 20 |
class: |
| 21 |
|
| 22 |
.. class:: Model(**kwargs) |
| 23 |
|
| 24 |
The keyword arguments are the names of the fields you've defined on your model. |
| 25 |
Note that instantiating a model in no way touches your database; for that, you |
| 26 |
need to :meth:`~Model.save()`. |
| 27 |
|
| 28 |
.. note:: |
| 29 |
|
| 30 |
You may be tempted to customize the model by overriding the ``__init__`` |
| 31 |
method. If you do so, however, take care not to change the calling |
| 32 |
signature as any change may prevent the model instance from being saved. |
| 33 |
Additionally, referring to model fields within ``__init__`` may potentially |
| 34 |
result in infinite recursion errors in some circumstances. Rather than |
| 35 |
overriding ``__init__``, try using one of these approaches: |
| 36 |
|
| 37 |
#. Add a classmethod on the model class:: |
| 38 |
|
| 39 |
from django.db import models |
| 40 |
|
| 41 |
|
| 42 |
class Book(models.Model): |
| 43 |
title = models.CharField(max_length=100) |
| 44 |
|
| 45 |
@classmethod |
| 46 |
def create(cls, title): |
| 47 |
book = cls(title=title) |
| 48 |
# do something with the book |
| 49 |
return book |
| 50 |
|
| 51 |
|
| 52 |
book = Book.create("Pride and Prejudice") |
| 53 |
|
| 54 |
#. Add a method on a custom manager (usually preferred):: |
| 55 |
|
| 56 |
class BookManager(models.Manager): |
| 57 |
def create_book(self, title): |
| 58 |
book = self.create(title=title) |
| 59 |
# do something with the book |
| 60 |
return book |
| 61 |
|
| 62 |
|
| 63 |
class Book(models.Model): |
| 64 |
title = models.CharField(max_length=100) |
| 65 |
|
| 66 |
objects = BookManager() |
| 67 |
|
| 68 |
|
| 69 |
book = Book.objects.create_book("Pride and Prejudice") |
| 70 |
|
| 71 |
Customizing model loading |
| 72 |
------------------------- |
| 73 |
|
| 74 |
.. classmethod:: Model.from_db(db, field_names, values) |
| 75 |
|
| 76 |
The ``from_db()`` method can be used to customize model instance creation |
| 77 |
when loading from the database. |
| 78 |
|
| 79 |
The ``db`` argument contains the database alias for the database the model |
| 80 |
is loaded from, ``field_names`` contains the names of all loaded fields, and |
| 81 |
``values`` contains the loaded values for each field in ``field_names``. The |
| 82 |
``field_names`` are in the same order as the ``values``. If all of the model's |
| 83 |
fields are present, then ``values`` are guaranteed to be in the order |
| 84 |
``__init__()`` expects them. That is, the instance can be created by |
| 85 |
``cls(*values)``. If any fields are deferred, they won't appear in |
| 86 |
``field_names``. In that case, assign a value of ``django.db.models.DEFERRED`` |
| 87 |
to each of the missing fields. |
| 88 |
|
| 89 |
In addition to creating the new model, the ``from_db()`` method must set the |
| 90 |
``adding`` and ``db`` flags in the new instance's :attr:`~Model._state` attribute. |
| 91 |
|
| 92 |
Below is an example showing how to record the initial values of fields that |
| 93 |
are loaded from the database:: |
| 94 |
|
| 95 |
from django.db.models import DEFERRED |
| 96 |
|
| 97 |
|
| 98 |
@classmethod |
| 99 |
def from_db(cls, db, field_names, values): |
| 100 |
# Default implementation of from_db() (subject to change and could |
| 101 |
# be replaced with super()). |
| 102 |
if len(values) != len(cls._meta.concrete_fields): |
| 103 |
values = list(values) |
| 104 |
values.reverse() |
| 105 |
values = [ |
| 106 |
values.pop() if f.attname in field_names else DEFERRED |
| 107 |
for f in cls._meta.concrete_fields |
| 108 |
] |
| 109 |
instance = cls(*values) |
| 110 |
instance._state.adding = False |
| 111 |
instance._state.db = db |
| 112 |
# customization to store the original field values on the instance |
| 113 |
instance._loaded_values = dict( |
| 114 |
zip(field_names, (value for value in values if value is not DEFERRED)) |
| 115 |
) |
| 116 |
return instance |
| 117 |
|
| 118 |
|
| 119 |
def save(self, **kwargs): |
| 120 |
# Check how the current values differ from ._loaded_values. For example, |
| 121 |
# prevent changing the creator_id of the model. (This example doesn't |
| 122 |
# support cases where 'creator_id' is deferred). |
| 123 |
if not self._state.adding and ( |
| 124 |
self.creator_id != self._loaded_values["creator_id"] |
| 125 |
): |
| 126 |
raise ValueError("Updating the value of creator isn't allowed") |
| 127 |
super().save(**kwargs) |
| 128 |
|
| 129 |
The example above shows a full ``from_db()`` implementation to clarify how that |
| 130 |
is done. In this case it would be possible to use a ``super()`` call in the |
| 131 |
``from_db()`` method. |
| 132 |
|
| 133 |
Refreshing objects from database |
| 134 |
================================ |
| 135 |
|
| 136 |
If you delete a field from a model instance, accessing it again reloads the |
| 137 |
value from the database: |
| 138 |
|
| 139 |
.. code-block:: pycon |
| 140 |
|
| 141 |
>>> obj = MyModel.objects.first() |
| 142 |
>>> del obj.field |
| 143 |
>>> obj.field # Loads the field from the database |
| 144 |
|
| 145 |
.. method:: Model.refresh_from_db(using=None, fields=None, from_queryset=None) |
| 146 |
.. method:: Model.arefresh_from_db(using=None, fields=None, from_queryset=None) |
| 147 |
|
| 148 |
*Asynchronous version*: ``arefresh_from_db()`` |
| 149 |
|
| 150 |
If you need to reload a model's values from the database, you can use the |
| 151 |
``refresh_from_db()`` method. When this method is called without arguments the |
| 152 |
following is done: |
| 153 |
|
| 154 |
#. All non-deferred fields of the model are updated to the values currently |
| 155 |
present in the database. |
| 156 |
#. Any cached relations are cleared from the reloaded instance. |
| 157 |
|
| 158 |
Only fields of the model are reloaded from the database. Other |
| 159 |
database-dependent values such as annotations aren't reloaded. Any |
| 160 |
:func:`@cached_property <django.utils.functional.cached_property>` attributes |
| 161 |
aren't cleared either. |
| 162 |
|
| 163 |
The reloading happens from the database the instance was loaded from, or from |
| 164 |
the default database if the instance wasn't loaded from the database. The |
| 165 |
``using`` argument can be used to force the database used for reloading. |
| 166 |
|
| 167 |
It is possible to force the set of fields to be loaded by using the ``fields`` |
| 168 |
argument. |
| 169 |
|
| 170 |
For example, to test that an ``update()`` call resulted in the expected |
| 171 |
update, you could write a test similar to this:: |
| 172 |
|
| 173 |
def test_update_result(self): |
| 174 |
obj = MyModel.objects.create(val=1) |
| 175 |
MyModel.objects.filter(pk=obj.pk).update(val=F("val") + 1) |
| 176 |
# At this point obj.val is still 1, but the value in the database |
| 177 |
# was updated to 2. The object's updated value needs to be reloaded |
| 178 |
# from the database. |
| 179 |
obj.refresh_from_db() |
| 180 |
self.assertEqual(obj.val, 2) |
| 181 |
|
| 182 |
Note that when deferred fields are accessed, the loading of the deferred |
| 183 |
field's value happens through this method. Thus it is possible to customize |
| 184 |
the way deferred loading happens. The example below shows how one can reload |
| 185 |
all of the instance's fields when a deferred field is reloaded:: |
| 186 |
|
| 187 |
class ExampleModel(models.Model): |
| 188 |
def refresh_from_db(self, using=None, fields=None, **kwargs): |
| 189 |
# fields contains the name of the deferred field to be |
| 190 |
# loaded. |
| 191 |
if fields is not None: |
| 192 |
fields = set(fields) |
| 193 |
deferred_fields = self.get_deferred_fields() |
| 194 |
# If any deferred field is going to be loaded |
| 195 |
if fields.intersection(deferred_fields): |
| 196 |
# then load all of them |
| 197 |
fields = fields.union(deferred_fields) |
| 198 |
super().refresh_from_db(using, fields, **kwargs) |
| 199 |
|
| 200 |
The ``from_queryset`` argument allows using a different queryset than the one |
| 201 |
created from :attr:`~django.db.models.Model._base_manager`. It gives you more |
| 202 |
control over how the model is reloaded. For example, when your model uses soft |
| 203 |
deletion you can make ``refresh_from_db()`` to take this into account:: |
| 204 |
|
| 205 |
obj.refresh_from_db(from_queryset=MyModel.active_objects.all()) |
| 206 |
|
| 207 |
You can cache related objects that otherwise would be cleared from the reloaded |
| 208 |
instance:: |
| 209 |
|
| 210 |
obj.refresh_from_db(from_queryset=MyModel.objects.select_related("related_field")) |
| 211 |
|
| 212 |
You can lock the row until the end of transaction before reloading a model's |
| 213 |
values:: |
| 214 |
|
| 215 |
obj.refresh_from_db(from_queryset=MyModel.objects.select_for_update()) |
| 216 |
|
| 217 |
.. versionchanged:: 5.1 |
| 218 |
|
| 219 |
The ``from_queryset`` argument was added. |
| 220 |
|
| 221 |
.. method:: Model.get_deferred_fields() |
| 222 |
|
| 223 |
A helper method that returns a set containing the attribute names of all those |
| 224 |
fields that are currently deferred for this model. |
| 225 |
|
| 226 |
.. _validating-objects: |
| 227 |
|
| 228 |
Validating objects |
| 229 |
================== |
| 230 |
|
| 231 |
There are four steps involved in validating a model: |
| 232 |
|
| 233 |
1. Validate the model fields - :meth:`Model.clean_fields()` |
| 234 |
2. Validate the model as a whole - :meth:`Model.clean()` |
| 235 |
3. Validate the field uniqueness - :meth:`Model.validate_unique()` |
| 236 |
4. Validate the constraints - :meth:`Model.validate_constraints` |
| 237 |
|
| 238 |
All four steps are performed when you call a model's :meth:`~Model.full_clean` |
| 239 |
method. |
| 240 |
|
| 241 |
When you use a :class:`~django.forms.ModelForm`, the call to |
| 242 |
:meth:`~django.forms.Form.is_valid()` will perform these validation steps for |
| 243 |
all the fields that are included on the form. See the :doc:`ModelForm |
| 244 |
documentation </topics/forms/modelforms>` for more information. You should only |
| 245 |
need to call a model's :meth:`~Model.full_clean()` method if you plan to handle |
| 246 |
validation errors yourself, or if you have excluded fields from the |
| 247 |
:class:`~django.forms.ModelForm` that require validation. |
| 248 |
|
| 249 |
.. method:: Model.full_clean(exclude=None, validate_unique=True, validate_constraints=True) |
| 250 |
|
| 251 |
This method calls :meth:`Model.clean_fields()`, :meth:`Model.clean()`, |
| 252 |
:meth:`Model.validate_unique()` (if ``validate_unique`` is ``True``), and |
| 253 |
:meth:`Model.validate_constraints()` (if ``validate_constraints`` is ``True``) |
| 254 |
in that order and raises a :exc:`~django.core.exceptions.ValidationError` that |
| 255 |
has a ``message_dict`` attribute containing errors from all four stages. |
| 256 |
|
| 257 |
The optional ``exclude`` argument can be used to provide a ``set`` of field |
| 258 |
names that can be excluded from validation and cleaning. |
| 259 |
:class:`~django.forms.ModelForm` uses this argument to exclude fields that |
| 260 |
aren't present on your form from being validated since any errors raised could |
| 261 |
not be corrected by the user. |
| 262 |
|
| 263 |
Note that ``full_clean()`` will *not* be called automatically when you call |
| 264 |
your model's :meth:`~Model.save()` method. You'll need to call it manually |
| 265 |
when you want to run one-step model validation for your own manually created |
| 266 |
models. For example:: |
| 267 |
|
| 268 |
from django.core.exceptions import ValidationError |
| 269 |
|
| 270 |
try: |
| 271 |
article.full_clean() |
| 272 |
except ValidationError as e: |
| 273 |
# Do something based on the errors contained in e.message_dict. |
| 274 |
# Display them to a user, or handle them programmatically. |
| 275 |
pass |
| 276 |
|
| 277 |
The first step ``full_clean()`` performs is to clean each individual field. |
| 278 |
|
| 279 |
.. method:: Model.clean_fields(exclude=None) |
| 280 |
|
| 281 |
This method will validate all fields on your model. The optional ``exclude`` |
| 282 |
argument lets you provide a ``set`` of field names to exclude from validation. |
| 283 |
It will raise a :exc:`~django.core.exceptions.ValidationError` if any fields |
| 284 |
fail validation. |
| 285 |
|
| 286 |
The second step ``full_clean()`` performs is to call :meth:`Model.clean()`. |
| 287 |
This method should be overridden to perform custom validation on your model. |
| 288 |
|
| 289 |
.. method:: Model.clean() |
| 290 |
|
| 291 |
This method should be used to provide custom model validation, and to modify |
| 292 |
attributes on your model if desired. For instance, you could use it to |
| 293 |
automatically provide a value for a field, or to do validation that requires |
| 294 |
access to more than a single field:: |
| 295 |
|
| 296 |
import datetime |
| 297 |
from django.core.exceptions import ValidationError |
| 298 |
from django.db import models |
| 299 |
from django.utils.translation import gettext_lazy as _ |
| 300 |
|
| 301 |
|
| 302 |
class Article(models.Model): |
| 303 |
... |
| 304 |
|
| 305 |
def clean(self): |
| 306 |
# Don't allow draft entries to have a pub_date. |
| 307 |
if self.status == "draft" and self.pub_date is not None: |
| 308 |
raise ValidationError(_("Draft entries may not have a publication date.")) |
| 309 |
# Set the pub_date for published items if it hasn't been set already. |
| 310 |
if self.status == "published" and self.pub_date is None: |
| 311 |
self.pub_date = datetime.date.today() |
| 312 |
|
| 313 |
Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()`` |
| 314 |
method is not invoked when you call your model's :meth:`~Model.save()` method. |
| 315 |
|
| 316 |
In the above example, the :exc:`~django.core.exceptions.ValidationError` |
| 317 |
exception raised by ``Model.clean()`` was instantiated with a string, so it |
| 318 |
will be stored in a special error dictionary key, |
| 319 |
:data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors |
| 320 |
that are tied to the entire model instead of to a specific field:: |
| 321 |
|
| 322 |
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError |
| 323 |
|
| 324 |
try: |
| 325 |
article.full_clean() |
| 326 |
except ValidationError as e: |
| 327 |
non_field_errors = e.message_dict[NON_FIELD_ERRORS] |
| 328 |
|
| 329 |
To assign exceptions to a specific field, instantiate the |
| 330 |
:exc:`~django.core.exceptions.ValidationError` with a dictionary, where the |
| 331 |
keys are the field names. We could update the previous example to assign the |
| 332 |
error to the ``pub_date`` field:: |
| 333 |
|
| 334 |
class Article(models.Model): |
| 335 |
... |
| 336 |
|
| 337 |
def clean(self): |
| 338 |
# Don't allow draft entries to have a pub_date. |
| 339 |
if self.status == "draft" and self.pub_date is not None: |
| 340 |
raise ValidationError( |
| 341 |
{"pub_date": _("Draft entries may not have a publication date.")} |
| 342 |
) |
| 343 |
... |
| 344 |
|
| 345 |
If you detect errors in multiple fields during ``Model.clean()``, you can also |
| 346 |
pass a dictionary mapping field names to errors:: |
| 347 |
|
| 348 |
raise ValidationError( |
| 349 |
{ |
| 350 |
"title": ValidationError(_("Missing title."), code="required"), |
| 351 |
"pub_date": ValidationError(_("Invalid date."), code="invalid"), |
| 352 |
} |
| 353 |
) |
| 354 |
|
| 355 |
Then, ``full_clean()`` will check unique constraints on your model. |
| 356 |
|
| 357 |
.. admonition:: How to raise field-specific validation errors if those fields don't appear in a ``ModelForm`` |
| 358 |
|
| 359 |
You can't raise validation errors in ``Model.clean()`` for fields that |
| 360 |
don't appear in a model form (a form may limit its fields using |
| 361 |
``Meta.fields`` or ``Meta.exclude``). Doing so will raise a ``ValueError`` |
| 362 |
because the validation error won't be able to be associated with the |
| 363 |
excluded field. |
| 364 |
|
| 365 |
To work around this dilemma, instead override :meth:`Model.clean_fields() |
| 366 |
<django.db.models.Model.clean_fields>` as it receives the list of fields |
| 367 |
that are excluded from validation. For example:: |
| 368 |
|
| 369 |
class Article(models.Model): |
| 370 |
... |
| 371 |
|
| 372 |
def clean_fields(self, exclude=None): |
| 373 |
super().clean_fields(exclude=exclude) |
| 374 |
if self.status == "draft" and self.pub_date is not None: |
| 375 |
if exclude and "status" in exclude: |
| 376 |
raise ValidationError( |
| 377 |
_("Draft entries may not have a publication date.") |
| 378 |
) |
| 379 |
else: |
| 380 |
raise ValidationError( |
| 381 |
{ |
| 382 |
"status": _( |
| 383 |
"Set status to draft if there is not a publication date." |
| 384 |
), |
| 385 |
} |
| 386 |
) |
| 387 |
|
| 388 |
.. method:: Model.validate_unique(exclude=None) |
| 389 |
|
| 390 |
This method is similar to :meth:`~Model.clean_fields`, but validates |
| 391 |
uniqueness constraints defined via :attr:`.Field.unique`, |
| 392 |
:attr:`.Field.unique_for_date`, :attr:`.Field.unique_for_month`, |
| 393 |
:attr:`.Field.unique_for_year`, or :attr:`Meta.unique_together |
| 394 |
<django.db.models.Options.unique_together>` on your model instead of individual |
| 395 |
field values. The optional ``exclude`` argument allows you to provide a ``set`` |
| 396 |
of field names to exclude from validation. It will raise a |
| 397 |
:exc:`~django.core.exceptions.ValidationError` if any fields fail validation. |
| 398 |
|
| 399 |
:class:`~django.db.models.UniqueConstraint`\s defined in the |
| 400 |
:attr:`Meta.constraints <django.db.models.Options.constraints>` are validated |
| 401 |
by :meth:`Model.validate_constraints`. |
| 402 |
|
| 403 |
Note that if you provide an ``exclude`` argument to ``validate_unique()``, any |
| 404 |
:attr:`~django.db.models.Options.unique_together` constraint involving one of |
| 405 |
the fields you provided will not be checked. |
| 406 |
|
| 407 |
Finally, ``full_clean()`` will check any other constraints on your model. |
| 408 |
|
| 409 |
.. method:: Model.validate_constraints(exclude=None) |
| 410 |
|
| 411 |
This method validates all constraints defined in |
| 412 |
:attr:`Meta.constraints <django.db.models.Options.constraints>`. The |
| 413 |
optional ``exclude`` argument allows you to provide a ``set`` of field names to |
| 414 |
exclude from validation. It will raise a |
| 415 |
:exc:`~django.core.exceptions.ValidationError` if any constraints fail |
| 416 |
validation. |
| 417 |
|
| 418 |
Saving objects |
| 419 |
============== |
| 420 |
|
| 421 |
To save an object back to the database, call ``save()``: |
| 422 |
|
| 423 |
.. method:: Model.save(*, force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None) |
| 424 |
.. method:: Model.asave(*, force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None) |
| 425 |
|
| 426 |
*Asynchronous version*: ``asave()`` |
| 427 |
|
| 428 |
For details on using the ``force_insert`` and ``force_update`` arguments, see |
| 429 |
:ref:`ref-models-force-insert`. Details about the ``update_fields`` argument |
| 430 |
can be found in the :ref:`ref-models-update-fields` section. |
| 431 |
|
| 432 |
If you want customized saving behavior, you can override this ``save()`` |
| 433 |
method. See :ref:`overriding-model-methods` for more details. |
| 434 |
|
| 435 |
The model save process also has some subtleties; see the sections below. |
| 436 |
|
| 437 |
.. deprecated:: 5.1 |
| 438 |
|
| 439 |
Support for positional arguments is deprecated. |
| 440 |
|
| 441 |
Auto-incrementing primary keys |
| 442 |
------------------------------ |
| 443 |
|
| 444 |
If a model has an :class:`~django.db.models.AutoField` — an auto-incrementing |
| 445 |
primary key — then that auto-incremented value will be calculated and saved as |
| 446 |
an attribute on your object the first time you call ``save()``: |
| 447 |
|
| 448 |
.. code-block:: pycon |
| 449 |
|
| 450 |
>>> b2 = Blog(name="Cheddar Talk", tagline="Thoughts on cheese.") |
| 451 |
>>> b2.id # Returns None, because b2 doesn't have an ID yet. |
| 452 |
>>> b2.save() |
| 453 |
>>> b2.id # Returns the ID of your new object. |
| 454 |
|
| 455 |
There's no way to tell what the value of an ID will be before you call |
| 456 |
``save()``, because that value is calculated by your database, not by Django. |
| 457 |
|
| 458 |
For convenience, each model has an :class:`~django.db.models.AutoField` named |
| 459 |
``id`` by default unless you explicitly specify ``primary_key=True`` on a field |
| 460 |
in your model. See the documentation for :class:`~django.db.models.AutoField` |
| 461 |
for more details. |
| 462 |
|
| 463 |
The ``pk`` property |
| 464 |
~~~~~~~~~~~~~~~~~~~ |
| 465 |
|
| 466 |
.. attribute:: Model.pk |
| 467 |
|
| 468 |
Regardless of whether you define a primary key field yourself, or let Django |
| 469 |
supply one for you, each model will have a property called ``pk``. It behaves |
| 470 |
like a normal attribute on the model, but is actually an alias for whichever |
| 471 |
field or fields compose the primary key for the model. You can read and set |
| 472 |
this value, just as you would for any other attribute, and it will update the |
| 473 |
correct fields in the model. |
| 474 |
|
| 475 |
.. versionchanged:: 5.2 |
| 476 |
|
| 477 |
Support for the primary key to be composed of multiple fields was added via |
| 478 |
``CompositePrimaryKey``. |
| 479 |
|
| 480 |
Explicitly specifying auto-primary-key values |
| 481 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 482 |
|
| 483 |
If a model has an :class:`~django.db.models.AutoField` but you want to define a |
| 484 |
new object's ID explicitly when saving, define it explicitly before saving, |
| 485 |
rather than relying on the auto-assignment of the ID: |
| 486 |
|
| 487 |
.. code-block:: pycon |
| 488 |
|
| 489 |
>>> b3 = Blog(id=3, name="Cheddar Talk", tagline="Thoughts on cheese.") |
| 490 |
>>> b3.id # Returns 3. |
| 491 |
>>> b3.save() |
| 492 |
>>> b3.id # Returns 3. |
| 493 |
|
| 494 |
If you assign auto-primary-key values manually, make sure not to use an |
| 495 |
already-existing primary-key value! If you create a new object with an explicit |
| 496 |
primary-key value that already exists in the database, Django will assume you're |
| 497 |
changing the existing record rather than creating a new one. |
| 498 |
|
| 499 |
Given the above ``'Cheddar Talk'`` blog example, this example would override the |
| 500 |
previous record in the database:: |
| 501 |
|
| 502 |
b4 = Blog(id=3, name="Not Cheddar", tagline="Anything but cheese.") |
| 503 |
b4.save() # Overrides the previous blog with ID=3! |
| 504 |
|
| 505 |
See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this |
| 506 |
happens. |
| 507 |
|
| 508 |
Explicitly specifying auto-primary-key values is mostly useful for bulk-saving |
| 509 |
objects, when you're confident you won't have primary-key collision. |
| 510 |
|
| 511 |
If you're using PostgreSQL, the sequence associated with the primary key might |
| 512 |
need to be updated; see :ref:`manually-specified-autoincrement-pk`. |
| 513 |
|
| 514 |
What happens when you save? |
| 515 |
--------------------------- |
| 516 |
|
| 517 |
When you save an object, Django performs the following steps: |
| 518 |
|
| 519 |
#. **Emit a pre-save signal.** The :data:`~django.db.models.signals.pre_save` |
| 520 |
signal is sent, allowing any functions listening for that signal to do |
| 521 |
something. |
| 522 |
|
| 523 |
#. **Preprocess the data.** Each field's |
| 524 |
:meth:`~django.db.models.Field.pre_save` method is called to perform any |
| 525 |
automated data modification that's needed. For example, the date/time fields |
| 526 |
override ``pre_save()`` to implement |
| 527 |
:attr:`~django.db.models.DateField.auto_now_add` and |
| 528 |
:attr:`~django.db.models.DateField.auto_now`. |
| 529 |
|
| 530 |
#. **Prepare the data for the database.** Each field's |
| 531 |
:meth:`~django.db.models.Field.get_db_prep_save` method is asked to provide |
| 532 |
its current value in a data type that can be written to the database. |
| 533 |
|
| 534 |
Most fields don't require data preparation. Simple data types, such as |
| 535 |
integers and strings, are 'ready to write' as a Python object. However, more |
| 536 |
complex data types often require some modification. |
| 537 |
|
| 538 |
For example, :class:`~django.db.models.DateField` fields use a Python |
| 539 |
``datetime`` object to store data. Databases don't store ``datetime`` |
| 540 |
objects, so the field value must be converted into an ISO-compliant date |
| 541 |
string for insertion into the database. |
| 542 |
|
| 543 |
#. **Insert the data into the database.** The preprocessed, prepared data is |
| 544 |
composed into an SQL statement for insertion into the database. |
| 545 |
|
| 546 |
#. **Emit a post-save signal.** The :data:`~django.db.models.signals.post_save` |
| 547 |
signal is sent, allowing any functions listening for that signal to do |
| 548 |
something. |
| 549 |
|
| 550 |
How Django knows to UPDATE vs. INSERT |
| 551 |
------------------------------------- |
| 552 |
|
| 553 |
You may have noticed Django database objects use the same ``save()`` method |
| 554 |
for creating and changing objects. Django abstracts the need to use ``INSERT`` |
| 555 |
or ``UPDATE`` SQL statements. Specifically, when you call ``save()`` and the |
| 556 |
object's primary key attribute does **not** define a |
| 557 |
:attr:`~django.db.models.Field.default` or |
| 558 |
:attr:`~django.db.models.Field.db_default`, Django follows this algorithm: |
| 559 |
|
| 560 |
* If the object's primary key attribute is set to anything except ``None``, |
| 561 |
Django executes an ``UPDATE``. |
| 562 |
* If the object's primary key attribute is *not* set or if the ``UPDATE`` |
| 563 |
didn't update anything (e.g. if primary key is set to a value that doesn't |
| 564 |
exist in the database), Django executes an ``INSERT``. |
| 565 |
|
| 566 |
If the object's primary key attribute defines a |
| 567 |
:attr:`~django.db.models.Field.default` or |
| 568 |
:attr:`~django.db.models.Field.db_default` then Django executes an ``UPDATE`` |
| 569 |
if it is an existing model instance and primary key is set to a value that |
| 570 |
exists in the database. Otherwise, Django executes an ``INSERT``. |
| 571 |
|
| 572 |
The one gotcha here is that you should be careful not to specify a primary-key |
| 573 |
value explicitly when saving new objects, if you cannot guarantee the |
| 574 |
primary-key value is unused. For more on this nuance, see `Explicitly specifying |
| 575 |
auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below. |
| 576 |
|
| 577 |
In Django 1.5 and earlier, Django did a ``SELECT`` when the primary key |
| 578 |
attribute was set. If the ``SELECT`` found a row, then Django did an ``UPDATE``, |
| 579 |
otherwise it did an ``INSERT``. The old algorithm results in one more query in |
| 580 |
the ``UPDATE`` case. There are some rare cases where the database doesn't |
| 581 |
report that a row was updated even if the database contains a row for the |
| 582 |
object's primary key value. An example is the PostgreSQL ``ON UPDATE`` trigger |
| 583 |
which returns ``NULL``. In such cases it is possible to revert to the old |
| 584 |
algorithm by setting the :attr:`~django.db.models.Options.select_on_save` |
| 585 |
option to ``True``. |
| 586 |
|
| 587 |
.. _ref-models-force-insert: |
| 588 |
|
| 589 |
Forcing an INSERT or UPDATE |
| 590 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 591 |
|
| 592 |
In some rare circumstances, it's necessary to be able to force the |
| 593 |
:meth:`~Model.save()` method to perform an SQL ``INSERT`` and not fall back to |
| 594 |
doing an ``UPDATE``. Or vice-versa: update, if possible, but not insert a new |
| 595 |
row. In these cases you can pass the ``force_insert=True`` or |
| 596 |
``force_update=True`` parameters to the :meth:`~Model.save()` method. |
| 597 |
Passing both parameters is an error: you cannot both insert *and* update at the |
| 598 |
same time! |
| 599 |
|
| 600 |
When using :ref:`multi-table inheritance <multi-table-inheritance>`, it's also |
| 601 |
possible to provide a tuple of parent classes to ``force_insert`` in order to |
| 602 |
force ``INSERT`` statements for each base. For example:: |
| 603 |
|
| 604 |
Restaurant(pk=1, name="Bob's Cafe").save(force_insert=(Place,)) |
| 605 |
|
| 606 |
Restaurant(pk=1, name="Bob's Cafe", rating=4).save(force_insert=(Place, Rating)) |
| 607 |
|
| 608 |
You can pass ``force_insert=(models.Model,)`` to force an ``INSERT`` statement |
| 609 |
for all parents. By default, ``force_insert=True`` only forces the insertion of |
| 610 |
a new row for the current model. |
| 611 |
|
| 612 |
It should be very rare that you'll need to use these parameters. Django will |
| 613 |
almost always do the right thing and trying to override that will lead to |
| 614 |
errors that are difficult to track down. This feature is for advanced use |
| 615 |
only. |
| 616 |
|
| 617 |
Using ``update_fields`` will force an update similarly to ``force_update``. |
| 618 |
|
| 619 |
.. _ref-models-field-updates-using-f-expressions: |
| 620 |
|
| 621 |
Updating attributes based on existing fields |
| 622 |
-------------------------------------------- |
| 623 |
|
| 624 |
Sometimes you'll need to perform a simple arithmetic task on a field, such |
| 625 |
as incrementing or decrementing the current value. One way of achieving this is |
| 626 |
doing the arithmetic in Python like: |
| 627 |
|
| 628 |
.. code-block:: pycon |
| 629 |
|
| 630 |
>>> product = Product.objects.get(name="Venezuelan Beaver Cheese") |
| 631 |
>>> product.number_sold += 1 |
| 632 |
>>> product.save() |
| 633 |
|
| 634 |
If the old ``number_sold`` value retrieved from the database was 10, then |
| 635 |
the value of 11 will be written back to the database. |
| 636 |
|
| 637 |
The process can be made robust, :ref:`avoiding a race condition |
| 638 |
<avoiding-race-conditions-using-f>`, as well as slightly faster by expressing |
| 639 |
the update relative to the original field value, rather than as an explicit |
| 640 |
assignment of a new value. Django provides :class:`F expressions |
| 641 |
<django.db.models.F>` for performing this kind of relative update. Using |
| 642 |
:class:`F expressions <django.db.models.F>`, the previous example is expressed |
| 643 |
as: |
| 644 |
|
| 645 |
.. code-block:: pycon |
| 646 |
|
| 647 |
>>> from django.db.models import F |
| 648 |
>>> product = Product.objects.get(name="Venezuelan Beaver Cheese") |
| 649 |
>>> product.number_sold = F("number_sold") + 1 |
| 650 |
>>> product.save() |
| 651 |
|
| 652 |
For more details, see the documentation on :class:`F expressions |
| 653 |
<django.db.models.F>` and their :ref:`use in update queries |
| 654 |
<topics-db-queries-update>`. |
| 655 |
|
| 656 |
.. _ref-models-update-fields: |
| 657 |
|
| 658 |
Specifying which fields to save |
| 659 |
------------------------------- |
| 660 |
|
| 661 |
If ``save()`` is passed a list of field names in keyword argument |
| 662 |
``update_fields``, only the fields named in that list will be updated. |
| 663 |
This may be desirable if you want to update just one or a few fields on |
| 664 |
an object. There will be a slight performance benefit from preventing |
| 665 |
all of the model fields from being updated in the database. For example:: |
| 666 |
|
| 667 |
product.name = "Name changed again" |
| 668 |
product.save(update_fields=["name"]) |
| 669 |
|
| 670 |
The ``update_fields`` argument can be any iterable containing strings. An |
| 671 |
empty ``update_fields`` iterable will skip the save. A value of ``None`` will |
| 672 |
perform an update on all fields. |
| 673 |
|
| 674 |
Specifying ``update_fields`` will force an update. |
| 675 |
|
| 676 |
When saving a model fetched through deferred model loading |
| 677 |
(:meth:`~django.db.models.query.QuerySet.only()` or |
| 678 |
:meth:`~django.db.models.query.QuerySet.defer()`) only the fields loaded |
| 679 |
from the DB will get updated. In effect there is an automatic |
| 680 |
``update_fields`` in this case. If you assign or change any deferred field |
| 681 |
value, the field will be added to the updated fields. |
| 682 |
|
| 683 |
.. admonition:: ``Field.pre_save()`` and ``update_fields`` |
| 684 |
|
| 685 |
If ``update_fields`` is passed in, only the |
| 686 |
:meth:`~django.db.models.Field.pre_save` methods of the ``update_fields`` |
| 687 |
are called. For example, this means that date/time fields with |
| 688 |
``auto_now=True`` will not be updated unless they are included in the |
| 689 |
``update_fields``. |
| 690 |
|
| 691 |
Deleting objects |
| 692 |
================ |
| 693 |
|
| 694 |
.. method:: Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False) |
| 695 |
.. method:: Model.adelete(using=DEFAULT_DB_ALIAS, keep_parents=False) |
| 696 |
|
| 697 |
*Asynchronous version*: ``adelete()`` |
| 698 |
|
| 699 |
Issues an SQL ``DELETE`` for the object. This only deletes the object in the |
| 700 |
database; the Python instance will still exist and will still have data in |
| 701 |
its fields, except for the primary key set to ``None``. This method returns the |
| 702 |
number of objects deleted and a dictionary with the number of deletions per |
| 703 |
object type. |
| 704 |
|
| 705 |
For more details, including how to delete objects in bulk, see |
| 706 |
:ref:`topics-db-queries-delete`. |
| 707 |
|
| 708 |
If you want customized deletion behavior, you can override the ``delete()`` |
| 709 |
method. See :ref:`overriding-model-methods` for more details. |
| 710 |
|
| 711 |
Sometimes with :ref:`multi-table inheritance <multi-table-inheritance>` you may |
| 712 |
want to delete only a child model's data. Specifying ``keep_parents=True`` will |
| 713 |
keep the parent model's data. |
| 714 |
|
| 715 |
Pickling objects |
| 716 |
================ |
| 717 |
|
| 718 |
When you :mod:`pickle` a model, its current state is pickled. When you unpickle |
| 719 |
it, it'll contain the model instance at the moment it was pickled, rather than |
| 720 |
the data that's currently in the database. |
| 721 |
|
| 722 |
.. admonition:: You can't share pickles between versions |
| 723 |
|
| 724 |
Pickles of models are only valid for the version of Django that |
| 725 |
was used to generate them. If you generate a pickle using Django |
| 726 |
version N, there is no guarantee that pickle will be readable with |
| 727 |
Django version N+1. Pickles should not be used as part of a long-term |
| 728 |
archival strategy. |
| 729 |
|
| 730 |
Since pickle compatibility errors can be difficult to diagnose, such as |
| 731 |
silently corrupted objects, a ``RuntimeWarning`` is raised when you try to |
| 732 |
unpickle a model in a Django version that is different than the one in |
| 733 |
which it was pickled. |
| 734 |
|
| 735 |
.. _model-instance-methods: |
| 736 |
|
| 737 |
Other model instance methods |
| 738 |
============================ |
| 739 |
|
| 740 |
A few object methods have special purposes. |
| 741 |
|
| 742 |
``__str__()`` |
| 743 |
------------- |
| 744 |
|
| 745 |
.. method:: Model.__str__() |
| 746 |
|
| 747 |
The ``__str__()`` method is called whenever you call ``str()`` on an object. |
| 748 |
Django uses ``str(obj)`` in a number of places. Most notably, to display an |
| 749 |
object in the Django admin site and as the value inserted into a template when |
| 750 |
it displays an object. Thus, you should always return a nice, human-readable |
| 751 |
representation of the model from the ``__str__()`` method. |
| 752 |
|
| 753 |
For example:: |
| 754 |
|
| 755 |
from django.db import models |
| 756 |
|
| 757 |
|
| 758 |
class Person(models.Model): |
| 759 |
first_name = models.CharField(max_length=50) |
| 760 |
last_name = models.CharField(max_length=50) |
| 761 |
|
| 762 |
def __str__(self): |
| 763 |
return f"{self.first_name} {self.last_name}" |
| 764 |
|
| 765 |
``__eq__()`` |
| 766 |
------------ |
| 767 |
|
| 768 |
.. method:: Model.__eq__() |
| 769 |
|
| 770 |
The equality method is defined such that instances with the same primary |
| 771 |
key value and the same concrete class are considered equal, except that |
| 772 |
instances with a primary key value of ``None`` aren't equal to anything except |
| 773 |
themselves. For proxy models, concrete class is defined as the model's first |
| 774 |
non-proxy parent; for all other models it's simply the model's class. |
| 775 |
|
| 776 |
For example:: |
| 777 |
|
| 778 |
from django.db import models |
| 779 |
|
| 780 |
|
| 781 |
class MyModel(models.Model): |
| 782 |
id = models.AutoField(primary_key=True) |
| 783 |
|
| 784 |
|
| 785 |
class MyProxyModel(MyModel): |
| 786 |
class Meta: |
| 787 |
proxy = True |
| 788 |
|
| 789 |
|
| 790 |
class MultitableInherited(MyModel): |
| 791 |
pass |
| 792 |
|
| 793 |
|
| 794 |
# Primary keys compared |
| 795 |
MyModel(id=1) == MyModel(id=1) |
| 796 |
MyModel(id=1) != MyModel(id=2) |
| 797 |
# Primary keys are None |
| 798 |
MyModel(id=None) != MyModel(id=None) |
| 799 |
# Same instance |
| 800 |
instance = MyModel(id=None) |
| 801 |
instance == instance |
| 802 |
# Proxy model |
| 803 |
MyModel(id=1) == MyProxyModel(id=1) |
| 804 |
# Multi-table inheritance |
| 805 |
MyModel(id=1) != MultitableInherited(id=1) |
| 806 |
|
| 807 |
``__hash__()`` |
| 808 |
-------------- |
| 809 |
|
| 810 |
.. method:: Model.__hash__() |
| 811 |
|
| 812 |
The ``__hash__()`` method is based on the instance's primary key value. It |
| 813 |
is effectively ``hash(obj.pk)``. If the instance doesn't have a primary key |
| 814 |
value then a ``TypeError`` will be raised (otherwise the ``__hash__()`` |
| 815 |
method would return different values before and after the instance is |
| 816 |
saved, but changing the :meth:`~object.__hash__` value of an instance is |
| 817 |
forbidden in Python. |
| 818 |
|
| 819 |
``get_absolute_url()`` |
| 820 |
---------------------- |
| 821 |
|
| 822 |
.. method:: Model.get_absolute_url() |
| 823 |
|
| 824 |
Define a ``get_absolute_url()`` method to tell Django how to calculate the |
| 825 |
canonical URL for an object. To callers, this method should appear to return a |
| 826 |
string that can be used to refer to the object over HTTP. |
| 827 |
|
| 828 |
For example:: |
| 829 |
|
| 830 |
def get_absolute_url(self): |
| 831 |
return "/people/%i/" % self.id |
| 832 |
|
| 833 |
While this code is correct and simple, it may not be the most portable way to |
| 834 |
to write this kind of method. The :func:`~django.urls.reverse` function is |
| 835 |
usually the best approach. |
| 836 |
|
| 837 |
For example:: |
| 838 |
|
| 839 |
def get_absolute_url(self): |
| 840 |
from django.urls import reverse |
| 841 |
|
| 842 |
return reverse("people-detail", kwargs={"pk": self.pk}) |
| 843 |
|
| 844 |
One place Django uses ``get_absolute_url()`` is in the admin app. If an object |
| 845 |
defines this method, the object-editing page will have a "View on site" link |
| 846 |
that will jump you directly to the object's public view, as given by |
| 847 |
``get_absolute_url()``. |
| 848 |
|
| 849 |
Similarly, a couple of other bits of Django, such as the :doc:`syndication feed |
| 850 |
framework </ref/contrib/syndication>`, use ``get_absolute_url()`` when it is |
| 851 |
defined. If it makes sense for your model's instances to each have a unique |
| 852 |
URL, you should define ``get_absolute_url()``. |
| 853 |
|
| 854 |
.. warning:: |
| 855 |
|
| 856 |
You should avoid building the URL from unvalidated user input, in order to |
| 857 |
reduce possibilities of link or redirect poisoning:: |
| 858 |
|
| 859 |
def get_absolute_url(self): |
| 860 |
return "/%s/" % self.name |
| 861 |
|
| 862 |
If ``self.name`` is ``'/example.com'`` this returns ``'//example.com/'`` |
| 863 |
which, in turn, is a valid schema relative URL but not the expected |
| 864 |
``'/%2Fexample.com/'``. |
| 865 |
|
| 866 |
|
| 867 |
It's good practice to use ``get_absolute_url()`` in templates, instead of |
| 868 |
hard-coding your objects' URLs. For example, this template code is bad: |
| 869 |
|
| 870 |
.. code-block:: html+django |
| 871 |
|
| 872 |
<!-- BAD template code. Avoid! --> |
| 873 |
<a href="/people/{{ object.id }}/">{{ object.name }}</a> |
| 874 |
|
| 875 |
This template code is much better: |
| 876 |
|
| 877 |
.. code-block:: html+django |
| 878 |
|
| 879 |
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a> |
| 880 |
|
| 881 |
The logic here is that if you change the URL structure of your objects, even |
| 882 |
for something small like correcting a spelling error, you don't want to have to |
| 883 |
track down every place that the URL might be created. Specify it once, in |
| 884 |
``get_absolute_url()`` and have all your other code call that one place. |
| 885 |
|
| 886 |
.. note:: |
| 887 |
The string you return from ``get_absolute_url()`` **must** contain only |
| 888 |
ASCII characters (required by the URI specification, :rfc:`3986#section-2`) |
| 889 |
and be URL-encoded, if necessary. |
| 890 |
|
| 891 |
Code and templates calling ``get_absolute_url()`` should be able to use the |
| 892 |
result directly without any further processing. You may wish to use the |
| 893 |
``django.utils.encoding.iri_to_uri()`` function to help with this if you |
| 894 |
are using strings containing characters outside the ASCII range. |
| 895 |
|
| 896 |
Extra instance methods |
| 897 |
====================== |
| 898 |
|
| 899 |
In addition to :meth:`~Model.save()`, :meth:`~Model.delete()`, a model object |
| 900 |
might have some of the following methods: |
| 901 |
|
| 902 |
.. method:: Model.get_FOO_display() |
| 903 |
|
| 904 |
For every field that has :attr:`~django.db.models.Field.choices` set, the |
| 905 |
object will have a ``get_FOO_display()`` method, where ``FOO`` is the name of |
| 906 |
the field. This method returns the "human-readable" value of the field. |
| 907 |
|
| 908 |
For example:: |
| 909 |
|
| 910 |
from django.db import models |
| 911 |
|
| 912 |
|
| 913 |
class Person(models.Model): |
| 914 |
SHIRT_SIZES = { |
| 915 |
"S": "Small", |
| 916 |
"M": "Medium", |
| 917 |
"L": "Large", |
| 918 |
} |
| 919 |
name = models.CharField(max_length=60) |
| 920 |
shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES) |
| 921 |
|
| 922 |
.. code-block:: pycon |
| 923 |
|
| 924 |
>>> p = Person(name="Fred Flintstone", shirt_size="L") |
| 925 |
>>> p.save() |
| 926 |
>>> p.shirt_size |
| 927 |
'L' |
| 928 |
>>> p.get_shirt_size_display() |
| 929 |
'Large' |
| 930 |
|
| 931 |
.. method:: Model.get_next_by_FOO(**kwargs) |
| 932 |
.. method:: Model.get_previous_by_FOO(**kwargs) |
| 933 |
|
| 934 |
For every :class:`~django.db.models.DateField` and |
| 935 |
:class:`~django.db.models.DateTimeField` that does not have :attr:`null=True |
| 936 |
<django.db.models.Field.null>`, the object will have ``get_next_by_FOO()`` and |
| 937 |
``get_previous_by_FOO()`` methods, where ``FOO`` is the name of the field. This |
| 938 |
returns the next and previous object with respect to the date field, raising |
| 939 |
a :exc:`~django.db.models.Model.DoesNotExist` exception when appropriate. |
| 940 |
|
| 941 |
Both of these methods will perform their queries using the default |
| 942 |
manager for the model. If you need to emulate filtering used by a |
| 943 |
custom manager, or want to perform one-off custom filtering, both |
| 944 |
methods also accept optional keyword arguments, which should be in the |
| 945 |
format described in :ref:`Field lookups <field-lookups>`. |
| 946 |
|
| 947 |
Note that in the case of identical date values, these methods will use the |
| 948 |
primary key as a tie-breaker. This guarantees that no records are skipped or |
| 949 |
duplicated. That also means you cannot use those methods on unsaved objects. |
| 950 |
|
| 951 |
.. admonition:: Overriding extra instance methods |
| 952 |
|
| 953 |
In most cases overriding or inheriting ``get_FOO_display()``, |
| 954 |
``get_next_by_FOO()``, and ``get_previous_by_FOO()`` should work as |
| 955 |
expected. Since they are added by the metaclass however, it is not |
| 956 |
practical to account for all possible inheritance structures. In more |
| 957 |
complex cases you should override ``Field.contribute_to_class()`` to set |
| 958 |
the methods you need. |
| 959 |
|
| 960 |
Other attributes |
| 961 |
================ |
| 962 |
|
| 963 |
``_state`` |
| 964 |
---------- |
| 965 |
|
| 966 |
.. attribute:: Model._state |
| 967 |
|
| 968 |
The ``_state`` attribute refers to a ``ModelState`` object that tracks |
| 969 |
the lifecycle of the model instance. |
| 970 |
|
| 971 |
The ``ModelState`` object has two attributes: ``adding``, a flag which is |
| 972 |
``True`` if the model has not been saved to the database yet, and ``db``, |
| 973 |
a string referring to the database alias the instance was loaded from or |
| 974 |
saved to. |
| 975 |
|
| 976 |
Newly instantiated instances have ``adding=True`` and ``db=None``, |
| 977 |
since they are yet to be saved. Instances fetched from a ``QuerySet`` |
| 978 |
will have ``adding=False`` and ``db`` set to the alias of the associated |
| 979 |
database. |
| 980 |
|
| 981 |
``_is_pk_set()`` |
| 982 |
---------------- |
| 983 |
|
| 984 |
.. method:: Model._is_pk_set() |
| 985 |
|
| 986 |
.. versionadded:: 5.2 |
| 987 |
|
| 988 |
The ``_is_pk_set()`` method returns whether the model instance's ``pk`` is set. |
| 989 |
It abstracts the model's primary key definition, ensuring consistent behavior |
| 990 |
regardless of the specific ``pk`` configuration. |