Model instance reference¶
This document describes the details of the Model
API. It builds on the
material presented in the model and database
query guides, so you’ll probably want to read and
understand those documents before reading this one.
Throughout this reference we’ll use the example Weblog models presented in the database query guide.
Creating objects¶
To create a new instance of a model, just instantiate it like any other Python class:
The keyword arguments are simply 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 save()
.
Informacja
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:
Add a classmethod on the model class:
from django.db import models 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")
Add a method on a custom manager (usually preferred):
class BookManager(models.Manager): def create_book(self, title): 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")
Customizing model loading¶
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
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.
In addition to creating the new model, the from_db()
method must set the
adding
and db
flags in the new instance’s _state
attribute.
Below is an example showing how to record the initial values of fields that are loaded from the database:
from django.db.models import DEFERRED
@classmethod
def from_db(cls, db, field_names, values):
# 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
]
instance = cls(*values)
instance._state.adding = False
instance._state.db = db
# customization to store the original field values on the instance
instance._loaded_values = dict(zip(field_names, values))
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")
super().save(*args, **kwargs)
The example above shows a full from_db()
implementation to clarify how that
is done. In this case it would of course be possible to just use super()
call
in the from_db()
method.
Refreshing objects from database¶
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
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:
- All non-deferred fields of the model are updated to the values currently present in the database.
- Any cached relations are cleared from the reloaded instance.
Only fields of the model are reloaded from the database. Other
database-dependent values such as annotations aren’t reloaded. Any
@cached_property
attributes
aren’t cleared either.
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)
super().refresh_from_db(using, fields, **kwargs)
A helper method that returns a set containing the attribute names of all those fields that are currently deferred for this model.
Validating objects¶
There are three steps involved in validating a model:
- Validate the model fields -
Model.clean_fields()
- Validate the model as a whole -
Model.clean()
- Validate the field uniqueness -
Model.validate_unique()
All three steps are performed when you call a model’s
full_clean()
method.
When you use a ModelForm
, the call to
is_valid()
will perform these validation steps for
all the fields that are included on the form. See the ModelForm
documentation for more information. You should only
need to call a model’s full_clean()
method if you plan to handle
validation errors yourself, or if you have excluded fields from the
ModelForm
that require validation.
This method calls Model.clean_fields()
, Model.clean()
, and
Model.validate_unique()
(if validate_unique
is True
), in that
order and raises a ValidationError
that has a
message_dict
attribute containing errors from all three stages.
The optional exclude
argument can be used to provide a list of field names
that can be excluded from validation and cleaning.
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.
Note that full_clean()
will not be called automatically when you call
your model’s 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:
from django.core.exceptions import ValidationError
try:
article.full_clean()
except ValidationError as e:
# Do something based on the errors contained in e.message_dict.
# Display them to a user, or handle them programmatically.
pass
The first step full_clean()
performs is to clean each individual field.
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
will raise a ValidationError
if any fields fail
validation.
The second step full_clean()
performs is to call Model.clean()
.
This method should be overridden to perform custom validation on your model.
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:
import datetime
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext_lazy as _
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:
raise ValidationError(_('Draft entries may not have a publication date.'))
# 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()
Note, however, that like Model.full_clean()
, a model’s clean()
method is not invoked when you call your model’s save()
method.
In the above example, the ValidationError
exception raised by Model.clean()
was instantiated with a string, so it
will be stored in a special error dictionary key,
NON_FIELD_ERRORS
. This key is used for errors
that are tied to the entire model instead of to a specific field:
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
try:
article.full_clean()
except ValidationError as e:
non_field_errors = e.message_dict[NON_FIELD_ERRORS]
To assign exceptions to a specific field, instantiate the
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:
raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')})
...
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'),
})
Finally, full_clean()
will check any unique constraints on your model.
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 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.'
),
})
This method is similar to 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
ValidationError
if any fields fail validation.
Note that if you provide an exclude
argument to validate_unique()
, any
unique_together
constraint involving one of
the fields you provided will not be checked.
Saving objects¶
To save an object back to the database, call save()
:
-
Model.
save
(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)[źródło]¶
If you want customized saving behavior, you can override this save()
method. See Nadpisywanie predefiniowanych metod modelu for more details.
The model save process also has some subtleties; see the sections below.
Auto-incrementing primary keys¶
If a model has an 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()
:
>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id # Returns None, because b2 doesn't have an ID yet.
>>> 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.
For convenience, each model has an AutoField
named
id
by default unless you explicitly specify primary_key=True
on a field
in your model. See the documentation for AutoField
for more details.
The pk
property¶
-
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 w