モデルインスタンスリファレンス¶
このドキュメントでは、Model
API の詳細を説明しています。モデル と データベースクエリ ガイドにある説明を前提としていますので、このドキュメントを読む前にこの 2 つを読んでおいた方がよいでしょう。
このドキュメント全体を通して、データベースクエリガイド で使った Weblog モデル例 を使用します。
オブジェクトを作成する¶
モデルの新しいインスタンスを作成するには、他の Python クラスと同様に単にインスタンス化してください:
キーワード引数は、シンプルに、モデル内で定義したフィールドの名前です。モデルをインスタンス化しても、データベースには何もしないことに注意してください。データベースとやり取りするには save()
を使う必要があります。
注釈
__init__
メソッドをオーバーライドしてモデルをカスタマイズする誘惑に駆られるかもしれません。その場合は、とは言え、あらゆる変更がモデルインスタンスを保存しないように、呼び出しシグネチャを変更しないように配慮してください。__init__
をオーバーライドするのではなく、以下のいずれかのアプローチを試してみてください:
モデルクラスにクラスメソッドを追加する:
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")
独自のマネジャーにメソッドを追加する (通常推奨される方法です):
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")
モデルの読み込みをカスタマイズする¶
from_db()
メソッドを使うと、データベースから読み込むときのモデルインスタンス作成をカスタマイズすることができます。
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
]
new = 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.
In older versions, you could check if all fields were loaded by consulting
cls._deferred
. This attribute is removed and
django.db.models.DEFERRED
is new.
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
In older versions, accessing a deleted field raised AttributeError
instead of reloading it.
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.
- The previously loaded related instances for which the relation’s value is no
longer valid are removed from the reloaded instance. For example, if you have
a foreign key from the reloaded instance to another model with name
Author
, then ifobj.author_id != obj.author.id
,obj.author
will be thrown away, and when next accessed it will be reloaded with the value ofobj.author_id
.
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(ExampleModel, self).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.
オブジェクトを検証 (バリデーション) する¶
モデルのバリデーションには 3 つのステップがあります:
モデルフィールドを検証する -
Model.clean_fields()
モデル全体を検証する -
Model.clean()
フィールドの一意性を検証する -
Model.validate_unique()
モデルの full_clean()
メソッドを使うと、3 つ全てのステップが実行されます。
ModelForm
を使っているとき、is_valid()
の呼び出しは、フォーム上に含まれる全てのフィールドに対して、これらの検証ステップを実行します。詳しくは ModelForm ドキュメント を参照してください。検証エラーを自分でコントロールしたい場合、もしくは ModelForm
から検証を必要とするフィールドを除外した場合は、モデルの full_clean()
メソッドだけを呼び出す必要があります。
このメソッドは、Model.clean_fields()
、Model.clean()
、そして Model.validate_unique()
(validate_unique
が True
の場合) をこの順序で呼び出し、3 つ全てのステージでのエラーを含む message_dict
属性を持つ ValidationError
を投げます。
省略可能な exclude
引数は、検証とクリーニングから除外するフィールド名のリストに使います。ModelForm
は、この引数をフォーム上に存在しないフィールドを検証対象から除外するために使います。これは、エラーが発生してもユーザーによって修正できないからです。
モデルの save()
メソッドを呼んだときでも full_clean()
は自動的に 呼ばれない ことに注意してください。手動で作ったモデルに対して 1 ステップでモデル検証をしたいときには、手動で呼び出す必要があります。例えば:
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
full_clean()
が行う最初のステップは、個々のフィールドをそれぞれクリーニングすることです。
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 ugettext_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 ValidationError, NON_FIELD_ERRORS
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.
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.
オブジェクトを保存する¶
データベースにオブジェクトを保存し直すには、save()
を呼び出します:
-
Model.
save
(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)[ソース]¶
保存の動作をカスタマイズしたい場合は、save()
メソッドをオーバーライドできます。詳しくは Overriding predefined model methods を参照してください。
モデル保存のプロセスには、いくつかの細かな注意点もあります; 以下の各セクションを参照してください。
自動インクリメントのプライマリキー¶
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 b 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.
pk
プロパティ¶
-
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¶
If a model has an AutoField
but you want to define a
new object’s ID explicitly when saving, just define it explicitly before
saving, rather than relying on the auto-assignment of the ID:
>>> 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.
What happens when you save?¶
When you save an object, Django performs the following steps:
Emit a pre-save signal. The
pre_save
signal is sent, allowing any functions listening for that signal to do something.Preprocess the data. Each field’s
pre_save()
method is called to perform any automated data modification that’s needed. For example, the date/time fields overridepre_save()
to implementauto_now_add
andauto_now
.Prepare the data for the database. Each field’s
get_db_prep_save()
method is asked to provide its current value in a data type that can be written to the database.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.
For example,
DateField
fields use a Pythondatetime
object to store data. Databases don’t storedatetime
objects, so the field value must be converted into an ISO-compliant date string for insertion into the database.Insert the data into the database. The preprocessed, prepared data is composed into an SQL statement for insertion into the database.
Emit a post-save signal. The
post_save
signal is sent, allowing any functions listening for that signal to do something.
Django が UPDATE と INSERT を見分ける方法¶
Django データベースオブジェクトが、オブジェクトの作成と変更に同じ save()
メソッドを使うことにお気づきかもしれません。Django は INSERT
や UPDATE
といった SQL ステートメントを抽象化しています。特に、save()
を呼び出すとき、Django は以下のアルゴリズムを実行します:
オブジェクトのプライマリキー属性が
True
と評価される値にセットされている場合 (例えばNone
や空の文字列以外の場合)。Django はUPDATE
を実行します。オブジェクトのプライマリキー属性がセット されていない、もしくは
UPDATE
が何もアップデートしなかった場合、Django はINSERT
を実行します。
ここで重要なのは、そのプライマリキーが使われていないことが保証できない場合、新しいオブジェクトを保存するときに明示的にプライマリキーの値を指定しないように気をつけることです。このニュアンスについては、上述の 自動プライマリキーの値を明示的に指定する と下記の INSERT や UPDATE を強制する を参照してください。
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 select_on_save
option to True
.
INSERT や UPDATE を強制する¶
まれに、save()
に対して SQL の INSERT
を強制してフォールバックで UPDATE
を実行しない (もしくは逆に: 可能ならば更新をして新しい行を追加しない) ように強制する必要があります。こうしたケースでは、force_insert=True
や force_update=True
パラメータを save()
メソッドに渡すことができます。当然のことですが、両方のパラメータを渡すとエラーになります: 追加と更新を同時にはできません!
これらのパラメータを必要とするのは、まれであるべきです。Django は、ほとんどの場合で正しく処理を行い、オーバーライドしようとすると追跡が難しいエラーの原因となります。この機能は応用的な場合のみに使用してください。
update_fields
を使うと force_update
と同じように更新を強制します。
既存のフィールドに基づいて属性を更新する¶
現在の値をインクリメントまたはデクリメントするなど、フィールドで単純な算術タスクを実行する必要が生じることがあります。 これを達成する明白な方法は、以下のようにすることです:
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold += 1
>>> product.save()
データベースから取得した古い number_sold
の値は 10 でした。そして、11 という値がデータベースに書き直されます。
このプロセスは、新しい値の明示的な割り当てではなく、元のフィールド値に対する更新を表現することによって、競合状態を回避しながら 堅牢にすることができます。 Djangoは、このような相対的な更新を行うための F expressions
を提供しています。 F expressions
を使用すると、上の例は以下のように表されます:
>>> from django.db.models import F
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold = F('number_sold') + 1
>>> product.save()
詳しくは、F expressions
とこれに対する 更新クエリ内で使う を参照してください。
どのフィールドを保存するか指定する¶
save()
にキーワード引数 update_fields
内でフィールドリストの名前が渡された場合、このリスト内で指定されたフィールドだけが更新されます。これは、オブジェクトの 1 つないし少数のフィールドだけを更新したい場合に望ましいでしょう。データベースで全てのモデルフィールドを更新しないようにすると、実行速度が少し向上します。例えば:
product.name = 'Name changed again'
product.save(update_fields=['name'])
update_fields
引数は文字列を含む任意のイテラブルです。空の update_fields
イテラブルは保存をスキップします。None という値は全てのフィールドを更新します。
update_fields
を指定すると更新を強制します。
遅延モデルローディング (only()
や defer()
) を通してフェッチされたモデルを保存するとき、DB からロードされたフィールドだけが更新されます。実際には、このケースでは自動的な update_fields
が存在します。遅延フィールドの値を追加もしくは変更した場合、フィールドは更新されたフィールドに追加されます。
オブジェクトを削除する¶
オブジェクトに対して SQL DELETE
を発行します。これはデータベースでオブジェクトの削除のみを行います; Python のインスタンスはなお存在しまたフィールド内にデータを持ち続けます。このメソッドは削除されるオブジェクトの数とオブジェクトタイプごとの削除の数のディクショナリを返します。
より詳しく (まとめてオブジェクトを削除する方法を含む) については、オブジェクトを削除する を参照してください。
独自の削除動作がほしいときは、delete()
メソッドをオーバーライドすることができます。詳しくは Overriding predefined model methods を参照してください。
Sometimes with 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.
The keep_parents
parameter was added.
The return value describing the number of objects deleted was added.
Pickling objects¶
When you 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.
Other model instance methods¶
A few object methods have special purposes.
__str__()
¶
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
representation of the model from the __str__()
method.
For example:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible # only if you need to support Python 2
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)
If you’d like compatibility with Python 2, you can decorate your model class
with python_2_unicode_compatible()
as shown above.
__eq__()
¶
The equality method is defined such that instances with the same primary
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.
For example:
from django.db import models
class MyModel(models.Model):
id = models.AutoField(primary_key=True)
class MyProxyModel(MyModel):
class Meta:
proxy = True
class MultitableInherited(MyModel):
pass
# Primary keys compared
MyModel(id=1) == MyModel(id=1)
MyModel(id=1) != MyModel(id=2)
# Primay keys are None
MyModel(id=None) != MyModel(id=None)
# Same instance
instance = MyModel(id=None)
instance == instance
# Proxy model
MyModel(id=1) == MyProxyModel(id=1)
# Multi-table inheritance
MyModel(id=1) != MultitableInherited(id=1)
__hash__()
¶
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__()
method would return different values before and after the instance is
saved, but changing the __hash__()
value of an instance is
forbidden in Python.
get_absolute_url()
¶
-
Model.
get_absolute_url
()¶
Define a get_absolute_url()
method to tell Django how to calculate the
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:
def get_absolute_url(self):
return "/people/%i/" % self.id
While this code is correct and simple, it may not be the most portable way to
to write this kind of method. The reverse()
function is
usually the best approach.
For example:
def get_absolute_url(self):
from django.urls import reverse
return reverse('people.views.details', args=[str(self.id)])
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
get_absolute_url()
.
Similarly, a couple of other bits of Django, such as the syndication feed
framework, 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()
.
警告
You should avoid building the URL from unvalidated user input, in order to 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/'
.
It’s good practice to use get_absolute_url()
in templates, instead of
hard-coding your objects’ URLs. For example, this template code is bad:
<!-- BAD template code. Avoid! -->
<a href="/people/{{ object.id }}/">{{ object.name }}</a>
This template code is much better:
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
The logic here is that if you change the URL structure of your objects, even
for something simple such as 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.
注釈
The string you return from get_absolute_url()
must contain only
ASCII characters (required by the URI specification, RFC 2396) and be
URL-encoded, if necessary.
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
django.utils.encoding.iri_to_uri()
function to help with this if you
are using unicode strings containing characters outside the ASCII range at
all.
Extra instance methods¶
In addition to save()
, delete()
, a model object
might have some of the following methods:
-
Model.
get_FOO_display
()¶
For every field that has choices
set, the
object will have a get_FOO_display()
method, where FOO
is the name of
the field. This method returns the “human-readable” value of the field.
For example:
from django.db import models
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
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
'L'
>>> p.get_shirt_size_display()
'Large'
-
Model.
get_next_by_FOO
(**kwargs)¶
-
Model.
get_previous_by_FOO
(**kwargs)¶
For every DateField
and
DateTimeField
that does not have null=True
, 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
a DoesNotExist
exception when appropriate.
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 Field lookups.
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.
Other attributes¶
DoesNotExist
¶
-
exception
Model.
DoesNotExist
¶ This exception is raised by the ORM in a couple places, for example by
QuerySet.get()
when an object is not found for the given query parameters.Django provides a
DoesNotExist
exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class withtry/except
. The exception is a subclass ofdjango.core.exceptions.ObjectDoesNotExist
.