Model instance reference

This document describes the details of the Model API. It builds on thematerial presented in the model and databasequery guides, so you'll probably want to read andunderstand those documents before reading this one.

在整篇参考中,我们将使用 数据库查询指南 中的 Weblog 示例模型

创建对象

To create a new instance of a model, just instantiate it like any other Pythonclass:

  • class Model(**kwargs)[源代码]
  • The keyword arguments are simply the names of the fields you've defined on yourmodel. Note that instantiating a model in no way touches your database; forthat, you need to save().

注解

You may be tempted to customize the model by overriding the initmethod. If you do so, however, take care not to change the callingsignature 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:
  1. from django.db import models
  2.  
  3. class Book(models.Model):
  4. title = models.CharField(max_length=100)
  5.  
  6. @classmethod
  7. def create(cls, title):
  8. book = cls(title=title)
  9. # do something with the book
  10. return book
  11.  
  12. book = Book.create("Pride and Prejudice")
  • Add a method on a custom manager (usually preferred):
  1. class BookManager(models.Manager):
  2. def create_book(self, title):
  3. book = self.create(title=title)
  4. # do something with the book
  5. return book
  6.  
  7. class Book(models.Model):
  8. title = models.CharField(max_length=100)
  9.  
  10. objects = BookManager()
  11.  
  12. book = Book.objects.create_book("Pride and Prejudice")

Customizing model loading

  • classmethod Model.fromdb(_db, field_names, values)[源代码]
  • The from_db() method can be used to customize model instance creationwhen loading from the database.

The db argument contains the database alias for the database the modelis loaded from, fieldnames contains the names of all loaded fields, andvalues contains the loaded values for each field in fieldnames. Thefield_names are in the same order as the values. If all of the model'sfields are present, then values are guaranteed to be in the order__init() expects them. That is, the instance can be created bycls(*values). If any fields are deferred, they won't appear infield_names. In that case, assign a value of django.db.models.DEFERREDto each of the missing fields.

In addition to creating the new model, the from_db() method must set theadding and db flags in the new instance's _state attribute.

Below is an example showing how to record the initial values of fields thatare loaded from the database:

  1. from django.db.models import DEFERRED
  2.  
  3. @classmethod
  4. def from_db(cls, db, field_names, values):
  5. # Default implementation of from_db() (subject to change and could
  6. # be replaced with super()).
  7. if len(values) != len(cls._meta.concrete_fields):
  8. values = list(values)
  9. values.reverse()
  10. values = [
  11. values.pop() if f.attname in field_names else DEFERRED
  12. for f in cls._meta.concrete_fields
  13. ]
  14. instance = cls(*values)
  15. instance._state.adding = False
  16. instance._state.db = db
  17. # customization to store the original field values on the instance
  18. instance._loaded_values = dict(zip(field_names, values))
  19. return instance
  20.  
  21. def save(self, *args, **kwargs):
  22. # Check how the current values differ from ._loaded_values. For example,
  23. # prevent changing the creator_id of the model. (This example doesn't
  24. # support cases where 'creator_id' is deferred).
  25. if not self._state.adding and (
  26. self.creator_id != self._loaded_values['creator_id']):
  27. raise ValueError("Updating the value of creator isn't allowed")
  28. super().save(*args, **kwargs)

The example above shows a full from_db() implementation to clarify how thatis done. In this case it would of course be possible to just use super() callin the from_db() method.

Refreshing objects from database

If you delete a field from a model instance, accessing it again reloads thevalue from the database:

  1. >>> obj = MyModel.objects.first()
  2. >>> del obj.field
  3. >>> obj.field # Loads the field from the database
  • Model.refreshfrom_db(_using=None, fields=None)[源代码]
  • If you need to reload a model's values from the database, you can use therefresh_from_db() method. When this method is called without arguments thefollowing is done:

  • All non-deferred fields of the model are updated to the values currentlypresent in the database.

  • Any cached relations are cleared from the reloaded instance.Only fields of the model are reloaded from the database. Otherdatabase-dependent values such as annotations aren't reloaded. Any@cached_property attributesaren't cleared either.

The reloading happens from the database the instance was loaded from, or fromthe default database if the instance wasn't loaded from the database. Theusing 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 fieldsargument.

For example, to test that an update() call resulted in the expectedupdate, you could write a test similar to this:

  1. def test_update_result(self):
  2. obj = MyModel.objects.create(val=1)
  3. MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
  4. # At this point obj.val is still 1, but the value in the database
  5. # was updated to 2. The object's updated value needs to be reloaded
  6. # from the database.
  7. obj.refresh_from_db()
  8. self.assertEqual(obj.val, 2)

Note that when deferred fields are accessed, the loading of the deferredfield's value happens through this method. Thus it is possible to customizethe way deferred loading happens. The example below shows how one can reloadall of the instance's fields when a deferred field is reloaded:

  1. class ExampleModel(models.Model):
  2. def refresh_from_db(self, using=None, fields=None, **kwargs):
  3. # fields contains the name of the deferred field to be
  4. # loaded.
  5. if fields is not None:
  6. fields = set(fields)
  7. deferred_fields = self.get_deferred_fields()
  8. # If any deferred field is going to be loaded
  9. if fields.intersection(deferred_fields):
  10. # then load all of them
  11. fields = fields.union(deferred_fields)
  12. super().refresh_from_db(using, fields, **kwargs)
  • Model.get_deferred_fields()[源代码]
  • A helper method that returns a set containing the attribute names of all thosefields that are currently deferred for this model.

Validating objects

There are three steps involved in validating a model:

When you use a ModelForm, the call tois_valid() will perform these validation steps forall the fields that are included on the form. See the ModelFormdocumentation for more information. You should onlyneed to call a model's full_clean() method if you plan to handlevalidation errors yourself, or if you have excluded fields from theModelForm that require validation.

The optional exclude argument can be used to provide a list of field namesthat can be excluded from validation and cleaning.ModelForm uses this argument to exclude fields thataren't present on your form from being validated since any errors raised couldnot be corrected by the user.

Note that fullclean() will _not be called automatically when you callyour model's save() method. You'll need to call it manuallywhen you want to run one-step model validation for your own manually createdmodels. For example:

  1. from django.core.exceptions import ValidationError
  2. try:
  3. article.full_clean()
  4. except ValidationError as e:
  5. # Do something based on the errors contained in e.message_dict.
  6. # Display them to a user, or handle them programmatically.
  7. pass

The first step full_clean() performs is to clean each individual field.

  • Model.cleanfields(_exclude=None)[源代码]
  • This method will validate all fields on your model. The optional excludeargument lets you provide a list of field names to exclude from validation. Itwill raise a ValidationError if any fields failvalidation.

The second step full_clean() performs is to call Model.clean().This method should be overridden to perform custom validation on your model.

  • Model.clean()[源代码]
  • This method should be used to provide custom model validation, and to modifyattributes on your model if desired. For instance, you could use it toautomatically provide a value for a field, or to do validation that requiresaccess to more than a single field:
  1. import datetime
  2. from django.core.exceptions import ValidationError
  3. from django.db import models
  4. from django.utils.translation import gettext_lazy as _
  5.  
  6. class Article(models.Model):
  7. ...
  8. def clean(self):
  9. # Don't allow draft entries to have a pub_date.
  10. if self.status == 'draft' and self.pub_date is not None:
  11. raise ValidationError(_('Draft entries may not have a publication date.'))
  12. # Set the pub_date for published items if it hasn't been set already.
  13. if self.status == 'published' and self.pub_date is None:
  14. 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 ValidationErrorexception raised by Model.clean() was instantiated with a string, so itwill be stored in a special error dictionary key,NON_FIELD_ERRORS. This key is used for errorsthat are tied to the entire model instead of to a specific field:

  1. from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
  2. try:
  3. article.full_clean()
  4. except ValidationError as e:
  5. non_field_errors = e.message_dict[NON_FIELD_ERRORS]

To assign exceptions to a specific field, instantiate theValidationError with a dictionary, where thekeys are the field names. We could update the previous example to assign theerror to the pub_date field:

  1. class Article(models.Model):
  2. ...
  3. def clean(self):
  4. # Don't allow draft entries to have a pub_date.
  5. if self.status == 'draft' and self.pub_date is not None:
  6. raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')})
  7. ...

If you detect errors in multiple fields during Model.clean(), you can alsopass a dictionary mapping field names to errors:

  1. raise ValidationError({
  2. 'title': ValidationError(_('Missing title.'), code='required'),
  3. 'pub_date': ValidationError(_('Invalid date.'), code='invalid'),
  4. })

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 thatdon't appear in a model form (a form may limit its fields usingMeta.fields or Meta.exclude). Doing so will raise a ValueErrorbecause the validation error won't be able to be associated with theexcluded field.

To work around this dilemma, instead override Model.clean_fields() as it receives the list of fieldsthat are excluded from validation. For example:

  1. class Article(models.Model):
  2. ...
  3. def clean_fields(self, exclude=None):
  4. super().clean_fields(exclude=exclude)
  5. if self.status == 'draft' and self.pub_date is not None:
  6. if exclude and 'status' in exclude:
  7. raise ValidationError(
  8. _('Draft entries may not have a publication date.')
  9. )
  10. else:
  11. raise ValidationError({
  12. 'status': _(
  13. 'Set status to draft if there is not a '
  14. 'publication date.'
  15. ),
  16. })
  • Model.validateunique(_exclude=None)[源代码]
  • This method is similar to clean_fields(), but validates alluniqueness constraints on your model instead of individual field values. Theoptional exclude argument allows you to provide a list of field names toexclude from validation. It will raise aValidationError if any fields fail validation.

Note that if you provide an exclude argument to validate_unique(), anyunique_together constraint involving one ofthe 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)[源代码]
  • If you want customized saving behavior, you can override this save()method. See 重写之前定义的模型方法 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-incrementingprimary key — then that auto-incremented value will be calculated and saved asan attribute on your object the first time you call save():

  1. >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
  2. >>> b2.id # Returns None, because b2 doesn't have an ID yet.
  3. >>> b2.save()
  4. >>> 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 callsave(), because that value is calculated by your database, not by Django.

For convenience, each model has an AutoField namedid by default unless you explicitly specify primary_key=True on a fieldin your model. See the documentation for AutoFieldfor more details.

The pk property

  • Model.pk
  • Regardless of whether you define a primary key field yourself, or let Djangosupply one for you, each model will have a property called pk. It behaveslike a normal attribute on the model, but is actually an alias for whicheverattribute is the primary key field for the model. You can read and set thisvalue, just as you would for any other attribute, and it will update thecorrect field in the model.

Explicitly specifying auto-primary-key values

If a model has an AutoField but you want to define anew object's ID explicitly when saving, just define it explicitly beforesaving, rather than relying on the auto-assignment of the ID:

  1. >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
  2. >>> b3.id # Returns 3.
  3. >>> b3.save()
  4. >>> b3.id # Returns 3.

If you assign auto-primary-key values manually, make sure not to use analready-existing primary-key value! If you create a new object with an explicitprimary-key value that already exists in the database, Django will assume you'rechanging the existing record rather than creating a new one.

Given the above 'Cheddar Talk' blog example, this example would override theprevious record in the database:

  1. b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
  2. b4.save() # Overrides the previous blog with ID=3!

See How Django knows to UPDATE vs. INSERT, below, for the reason thishappens.

Explicitly specifying auto-primary-key values is mostly useful for bulk-savingobjects, when you're confident you won't have primary-key collision.

If you're using PostgreSQL, the sequence associated with the primary key mightneed to be updated; see Manually-specifying values of auto-incrementing primary keys.

What happens when you save?

When you save an object, Django performs the following steps:

  • Emit a pre-save signal. The pre_savesignal is sent, allowing any functions listening for that signal to dosomething.

  • Preprocess the data. Each field'spre_save() method is called to perform anyautomated data modification that's needed. For example, the date/time fieldsoverride pre_save() to implementauto_now_add andauto_now.

  • Prepare the data for the database. Each field'sget_db_prep_save() method is asked to provideits current value in a data type that can be written to the database.

Most fields don't require data preparation. Simple data types, such asintegers and strings, are 'ready to write' as a Python object. However, morecomplex data types often require some modification.

For example, DateField fields use a Pythondatetime object to store data. Databases don't store datetimeobjects, so the field value must be converted into an ISO-compliant datestring for insertion into the database.

  • Insert the data into the database. The preprocessed, prepared data iscomposed into an SQL statement for insertion into the database.

  • Emit a post-save signal. The post_savesignal is sent, allowing any functions listening for that signal to dosomething.

How Django knows to UPDATE vs. INSERT

You may have noticed Django database objects use the same save() methodfor creating and changing objects. Django abstracts the need to use INSERTor UPDATE SQL statements. Specifically, when you call save(), Djangofollows this algorithm:

  • If the object's primary key attribute is set to a value that evaluates toTrue (i.e., a value other than None or the empty string), Djangoexecutes an UPDATE.
  • If the object's primary key attribute is not set or if the UPDATEdidn't update anything (e.g. if primary key is set to a value that doesn'texist in the database), Django executes an INSERT.The one gotcha here is that you should be careful not to specify a primary-keyvalue explicitly when saving new objects, if you cannot guarantee theprimary-key value is unused. For more on this nuance, see Explicitly specifyingauto-primary-key values above and Forcing an INSERT or UPDATE below.

In Django 1.5 and earlier, Django did a SELECT when the primary keyattribute 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 inthe UPDATE case. There are some rare cases where the database doesn'treport that a row was updated even if the database contains a row for theobject's primary key value. An example is the PostgreSQL ON UPDATE triggerwhich returns NULL. In such cases it is possible to revert to the oldalgorithm by setting the select_on_saveoption to True.

Forcing an INSERT or UPDATE

In some rare circumstances, it's necessary to be able to force thesave() method to perform an SQL INSERT and not fall back todoing an UPDATE. Or vice-versa: update, if possible, but not insert a newrow. In these cases you can pass the force_insert=True orforce_update=True parameters to the save() method.Obviously, passing both parameters is an error: you cannot both insert _and_update at the same time!

It should be very rare that you'll need to use these parameters. Django willalmost always do the right thing and trying to override that will lead toerrors that are difficult to track down. This feature is for advanced useonly.

Using update_fields will force an update similarly to force_update.

Updating attributes based on existing fields

Sometimes you'll need to perform a simple arithmetic task on a field, suchas incrementing or decrementing the current value. The obvious way toachieve this is to do something like:

  1. >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
  2. >>> product.number_sold += 1
  3. >>> product.save()

If the old number_sold value retrieved from the database was 10, thenthe value of 11 will be written back to the database.

The process can be made robust, avoiding a race condition, as well as slightly faster by expressingthe update relative to the original field value, rather than as an explicitassignment of a new value. Django provides F expressions for performing this kind of relative update. UsingF expressions, the previous example is expressedas:

  1. >>> from django.db.models import F
  2. >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
  3. >>> product.number_sold = F('number_sold') + 1
  4. >>> product.save()

For more details, see the documentation on F expressions and their use in update queries.

Specifying which fields to save

If save() is passed a list of field names in keyword argumentupdate_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 onan object. There will be a slight performance benefit from preventingall of the model fields from being updated in the database. For example:

  1. product.name = 'Name changed again'
  2. product.save(update_fields=['name'])

The update_fields argument can be any iterable containing strings. Anempty update_fields iterable will skip the save. A value of None willperform an update on all fields.

Specifying update_fields will force an update.

When saving a model fetched through deferred model loading(only() ordefer()) only the fields loadedfrom the DB will get updated. In effect there is an automaticupdate_fields in this case. If you assign or change any deferred fieldvalue, the field will be added to the updated fields.

删除对象

  • Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False)[源代码]
  • Issues an SQL DELETE for the object. This only deletes the object in thedatabase; the Python instance will still exist and will still have data inits fields. This method returns the number of objects deleted and a dictionarywith the number of deletions per object type.

For more details, including how to delete objects in bulk, see删除对象.

If you want customized deletion behavior, you can override the delete()method. See 重写之前定义的模型方法 for more details.

Sometimes with multi-table inheritance you maywant to delete only a child model's data. Specifying keep_parents=True willkeep the parent model's data.

Pickling objects

When you pickle a model, its current state is pickled. When you unpickleit, it'll contain the model instance at the moment it was pickled, rather thanthe data that's currently in the database.

You can't share pickles between versions

Pickles of models are only valid for the version of Django thatwas used to generate them. If you generate a pickle using Djangoversion N, there is no guarantee that pickle will be readable withDjango version N+1. Pickles should not be used as part of a long-termarchival strategy.

Since pickle compatibility errors can be difficult to diagnose, such assilently corrupted objects, a RuntimeWarning is raised when you try tounpickle a model in a Django version that is different than the one inwhich it was pickled.

Other model instance methods

A few object methods have special purposes.

str()

  • Model.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 anobject in the Django admin site and as the value inserted into a template whenit displays an object. Thus, you should always return a nice, human-readablerepresentation of the model from the str() method.

例子:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. first_name = models.CharField(max_length=50)
  5. last_name = models.CharField(max_length=50)
  6.  
  7. def __str__(self):
  8. return '%s %s' % (self.first_name, self.last_name)

eq()

  • Model.eq()[源代码]
  • The equality method is defined such that instances with the same primarykey value and the same concrete class are considered equal, except thatinstances with a primary key value of None aren't equal to anything exceptthemselves. For proxy models, concrete class is defined as the model's firstnon-proxy parent; for all other models it's simply the model's class.

例子:

  1. from django.db import models
  2.  
  3. class MyModel(models.Model):
  4. id = models.AutoField(primary_key=True)
  5.  
  6. class MyProxyModel(MyModel):
  7. class Meta:
  8. proxy = True
  9.  
  10. class MultitableInherited(MyModel):
  11. pass
  12.  
  13. # Primary keys compared
  14. MyModel(id=1) == MyModel(id=1)
  15. MyModel(id=1) != MyModel(id=2)
  16. # Primary keys are None
  17. MyModel(id=None) != MyModel(id=None)
  18. # Same instance
  19. instance = MyModel(id=None)
  20. instance == instance
  21. # Proxy model
  22. MyModel(id=1) == MyProxyModel(id=1)
  23. # Multi-table inheritance
  24. MyModel(id=1) != MultitableInherited(id=1)

hash()

  • Model.hash()[源代码]
  • The hash() method is based on the instance's primary key value. Itis effectively hash(obj.pk). If the instance doesn't have a primary keyvalue then a TypeError will be raised (otherwise the hash()method would return different values before and after the instance issaved, but changing the hash() value of an instance isforbidden in Python.

get_absolute_url()

  • Model.get_absolute_url()
  • Define a get_absolute_url() method to tell Django how to calculate thecanonical URL for an object. To callers, this method should appear to return astring that can be used to refer to the object over HTTP.

例子:

  1. def get_absolute_url(self):
  2. return "/people/%i/" % self.id

While this code is correct and simple, it may not be the most portable way toto write this kind of method. The reverse() function isusually the best approach.

例子:

  1. def get_absolute_url(self):
  2. from django.urls import reverse
  3. return reverse('people.views.details', args=[str(self.id)])

One place Django uses get_absolute_url() is in the admin app. If an objectdefines this method, the object-editing page will have a "View on site" linkthat will jump you directly to the object's public view, as given byget_absolute_url().

Similarly, a couple of other bits of Django, such as the syndication feedframework, use get_absolute_url() when it isdefined. If it makes sense for your model's instances to each have a uniqueURL, you should define get_absolute_url().

警告

You should avoid building the URL from unvalidated user input, in order toreduce possibilities of link or redirect poisoning:

  1. def get_absolute_url(self):
  2. 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 ofhard-coding your objects' URLs. For example, this template code is bad:

  1. <!-- BAD template code. Avoid! -->
  2. <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, evenfor something simple such as correcting a spelling error, you don't want tohave 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 onlyASCII characters (required by the URI specification, RFC 2396) and beURL-encoded, if necessary.

Code and templates calling get_absolute_url() should be able to use theresult directly without any further processing. You may wish to use thedjango.utils.encoding.iri_to_uri() function to help with this if youare using strings containing characters outside the ASCII range.

Extra instance methods

In addition to save(), delete(), a model objectmight have some of the following methods:

  • Model.get_FOO_display()
  • For every field that has choices set, theobject will have a get_FOO_display() method, where FOO is the name ofthe field. This method returns the "human-readable" value of the field.

例子:

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.getnext_by_FOO(**kwargs_)
  • Model.getprevious_by_FOO(**kwargs_)
  • For every DateField andDateTimeField that does not have null=True, the object will have get_next_by_FOO() andget_previous_by_FOO() methods, where FOO is the name of the field. Thisreturns the next and previous object with respect to the date field, raisinga DoesNotExist exception when appropriate.

Both of these methods will perform their queries using the defaultmanager for the model. If you need to emulate filtering used by acustom manager, or want to perform one-off custom filtering, bothmethods also accept optional keyword arguments, which should be in theformat described in Field lookups.

Note that in the case of identical date values, these methods will use theprimary key as a tie-breaker. This guarantees that no records are skipped orduplicated. 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 byQuerySet.get() when an objectis not found for the given query parameters.

Django provides a DoesNotExist exception as an attribute of each modelclass to identify the class of object that could not be found and to allowyou to catch a particular model class with try/except. The exception isa subclass of django.core.exceptions.ObjectDoesNotExist.