Acuan contoh modelLink to this heading

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.

membuat obyekLink to this heading

To create a new instance of a model, instantiate it like any other Python class:

class Model(**kwargs)Link to this definition

The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().

Menyesuaikan memuat modelLink to this heading

classmethod Model.from_db(db, field_names, values)Link to this definition

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:

Code
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 use super() call in the from_db() method.

Menyegarkan kembali obyek dari basisdataLink to this heading

Jika anda menghapus sebuah bidang dari sebuah contoh model, mengakses itu kembali memuat kembali nilai dari basisdata:

Code
>>> obj = MyModel.objects.first()
>>> del obj.field
>>> obj.field  # Loads the field from the database
Model.refresh_from_db(using=None, fields=None)Link to this definition

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:

  1. All non-deferred fields of the model are updated to the values currently present in the database.

  2. Any cached relations are cleared from the reloaded instance.

Hanya bidang-bidang dari model dimuat kembali dari basisdata. Nilai-nilai bergantung-basisdata lain seperti keterangan tidak dimuat kembali. Atribut @cached_property apapun tidak dibersihkan juga.

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.

Itu memungkinkan untuk memaksa kumpulan dari bidang-bidang dimuat menggunakan argumen field.

Sebagai contoh, untuk mencoba bahwa sebuah panggilan update() dihasilkan dalam pembaharuan diharapkan, anda dapat menulis sebuah percobaan miriip seperti ini:

Code
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)

Catat bahwa ketika bidang ditangguhkan diakses, memuat nilai bidang tertangguh terjadi melalui metode ini. dengan demikian itu adalah mungkin untuk menyesuaian cara penangguhan memuat terjadi. Contoh dibawah menunjukkan bagaimana satu dapat dimuat kembali dari bidang-bidang instance ketika bidang tertangguhkan dimuat:

Code
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)
Model.get_deferred_fields()Link to this definition

A helper method that returns a set containing the attribute names of all those fields that are currently deferred for this model.

Mensahkan obyek-obyekLink to this heading

Ada tidak langkah terlibat dalam mengesahkan sebuah model:

  1. Mensahkan bidang-bidang model - Model.clean_fields()

  2. Mensahkan model sebagai sebuah keseluruhan - Model.clean_fields()

  3. Mensahkan keunikan bidang - Model.validate_unique()

Semua tiga langkah dilakukan ketika anda memanggil metode full_clean() model.

Ketika anda menggunakan ModelForm, panggilan pada is_valid() akan melakukan langkah-langkah pengesahan ini untuk semua bidang yang disertakan pada formulir. Lihat ModelForm documentation ` untuk informasi lebih. Anda hanya butuh memanggil metode :meth:`~Model.full_clean() model jika anda berencana menangani kesalahan pengesahan anda sendiri, atau jika anda telah tidak menyertakan bidang-bidang dari ModelForm yang membutuhkan pengesahan.

Model.full_clean(exclude=None, validate_unique=True)Link to this definition

Metode ini memanggil Model.clean_fields(), Model.clean(), dan Model.validate_unique() (jika validate_unique adalah True), dalam urutan itu dan memunculkan ValidationError yang mempunyai atribut message_dict mengandung kesalahan dari semua tiga tingkatan.

Argumen exclude pilihan dapat digunakan untuk menyediakan daftar dari nama-nama bidang yang dapat tidak disertakan dari pengesahan dan pembersihan. ModelForm menggunakan argumen ini untuk tidak menyertakan bidang-bidang yang tidak hadir pada formulir anda dari menjadi disahkan sejak kesalahan apapun muncul tidak dapat diperbaiki oleh pengguna.

Catata bahwa full_clean() tidak akan dipanggil otomatis ketika anda memanggil metode save() model anda. Anda akan butuh memanggil itu secara manual ketika anda ingin menjalankan pengesahan model satu-langkah untuk anda sendiri secara manual model dibuat. Sebagai contoh:

Code
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

Langkah pertama full_clean() lakukan adalah membersihkan setiap bidang masing-masing.

Model.clean_fields(exclude=None)Link to this definition

Metode ini akan mensahkan semua bidang pada model anda. Pilihan argumen exclude membuat anda menyediakan daftar dari nama-nama bidang untuk tidak disertakan dari pengesahan. itu akan memunculkan ValidationError jika bidang apapun gagal mensahkan.

Langkah kedua full_clean() lakukan adalah memanggil Model.clean(). Metode ini harus ditimpa untuk melakukan penyesuaian keabsahan pada model anda.

Model.clean()Link to this definition

Metode ini harus digunakan untuk menyediakan pengesahan model penyesuaian, dan untuk merubah atribut pada model anda jika diinginkan. Sebagai contoh, anda dapat menggunakan itu secara otomatis menyediakan nilai untuk bidang, atau melakukan pengesahan yang membutuhkan akses pada lebih dari bidang tunggal:

Code
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()

Catat, bagaimanapun, itu seeprti Model.full_clean(), sebuah metode clean() model tidak dipanggil ketika anda memanggil metode save() model anda.

Dalam contoh diatas, pengecualian ValidationError dimunculkan oleh Model.clean() telah dipakai dengan string, sehingga itu akan tetap disimpan dalam kunci dictionary khusus, NON_FIELD_ERRORS. Kunci ini digunakan untuk kesalahan-kesalahan yang diikat pada keseluruhan model daripada bidang tertentu:

Code
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]

Untuk memberikan pengecualian pada bidang khusus, pemakaian ValidationError dengan sebuah dictionary, dimana kunci-kunci adalah nama-nama bidang. Kami dapat memperbaharui contoh sebelumnya untuk memberikan kesalahan pada bidang pub_date:

Code
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.')})
        ...

Jika anda mengetahui kesalahan dalam banyak bidang selama Model.clean(), anda dapat juga melewatkan nama-nama bidang pemetaan dictionary pada kesalahan:

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

Akhirnya, full_clean() akan memeriksa batsan unik pada model.

Model.validate_unique(exclude=None)Link to this definition

Metode ini mirip pada clean_fields(), tetapi mensahkan semua batasan-batasan unik pada model anda daripada nilai bidang tersendiri. Argumen exclude pilihan mengizinkan anda menyediakan daftar dari nama-nama bidang untuk tidak menyertakan dari pengesahan. Itu akan memunculkan ValidationError jika bidang apapun gagal pengesahan.

Catat bahwa jika anda menyediakan sebuah argumen exclude pada validate_unique(), batasan unique_together apapun melibatkan satu dari bidang-bidang anda sediakan tidak akan diperiksa.

Menyimpan obyekLink to this heading

Untuk menyimpan sebuah obyek kembali ke basisdata, panggil save():

Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)Link to this definition

If you want customized saving behavior, you can override this save() method. See Menimpa metode model yang detetapkan for more details.

The model save process also has some subtleties; see the sections below.

Peningkatan-otomatis primary keyLink to this heading

Jika sebuah model mempunyai AutoField — sebuah primary key menaik-otomatis - kemudian nilai menaik-otomatis akan dihitung dan disimpan sebagai sebuah atribut pada obyek anda pertama kali anda memanggil save():

Code
>>> 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.

Untuk kenyamanan, setiap model memiliki sebuah AutoField bernama id secara awalan meskipun anda secara tegas menentukan primary_key=True pada bidang dalam model anda. Lihat dokumentasi untuk AutoField untuk rincian lebih.

Sifat pkLink to this heading

Model.pkLink to this definition

Meskipun apakah anda menentukan bidang primary key anda sendiri, atau membiarkan Django mendukung satu untuk anda, setiap model akan memiliki sifat dipanggil pk. Itu berperilaku seperti atribut biasa pada model, tetapi sebenarnya sebuah nama lain untuk atribut mana saja adalah bidang primary key untuk model. Anda dapat membaca dan mensetel nilai ini, sama seperti anda untuk atribut lain, dan itu akan memperbaharui bidang benar dalam model.

Explicitly specifying auto-primary-key valuesLink to this heading

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

Code
>>> 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.

Diberikan contoh blog 'Cheddar Talk' diatas, contoh ini akan menimpa rekaman sebelumnya di basisdata:

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

Lihat How Django knows to UPDATE vs. INSERT, dibawah, untuk alasan ini terjadi.

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

If you're using PostgreSQL, the sequence associated with the primary key might need to be updated; see Manual-menentukan nilai-nilai dari primary key peningkatan-otomatis.

Apa yang terjadi ketika anda menyimpan?Link to this heading

Ketika anda menyimpan sebuah obyek, Django melakukan langkah-langkah berikut:

  1. Emit a pre-save signal. The pre_save signal is sent, allowing any functions listening for that signal to do something.

  2. 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 override pre_save() to implement auto_now_add and auto_now.

  3. 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 Python datetime object to store data. Databases don't store datetime objects, so the field value must be converted into an ISO-compliant date string for insertion into the database.

  4. Insert the data into the database. The preprocessed, prepared data is composed into an SQL statement for insertion into the database.

  5. Emit a post-save signal. The post_save signal is sent, allowing any functions listening for that signal to do something.

Bagaimana Django mengetahui untuk UPDATE lawan INSERTLink to this heading

You may have noticed Django database objects use the same save() method for creating and changing objects. Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save() and the object's primary key attribute does not define a default, Django follows this algorithm:

  • If the object's primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE.

  • If the object's primary key attribute is not set or if the UPDATE didn't update anything (e.g. if primary key is set to a value that doesn't exist in the database), Django executes an INSERT.

If the object's primary key attribute defines a default then Django executes an UPDATE if it is an existing model instance and primary key is set to a value that exists in the database. Otherwise, Django executes an INSERT.

The one gotcha here is that you should be careful not to specify a primary-key value explicitly when saving new objects, if you cannot guarantee the primary-key value is unused. For more on this nuance, see Explicitly specifying auto-primary-key values above and Forcing an INSERT or UPDATE below.

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.

Memaksa sebuah INSERT atau UPDATELink to this heading

In some rare circumstances, it's necessary to be able to force the save() method to perform an SQL INSERT and not fall back to doing an UPDATE. Or vice-versa: update, if possible, but not insert a new row. In these cases you can pass the force_insert=True or force_update=True parameters to the save() method. 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 will almost always do the right thing and trying to override that will lead to errors that are difficult to track down. This feature is for advanced use only.

Menggunakan update_fields akan memaksa sebuah perbaharuan mirip pada force_update.

Memperbaharui atribut berdasarkan pada bidang yang adaLink to this heading

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

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

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

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

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

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

Menentukan bidang-bidang mana yang disimpanLink to this heading

If save() is passed a list of field names in keyword argument update_fields, only the fields named in that list will be updated. This may be desirable if you want to update just one or a few fields on an object. There will be a slight performance benefit from preventing all of the model fields from being updated in the database. For example:

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

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

Menentukan update_fields akan memaksa sebuah pembaharuan.

When saving a model fetched through deferred model loading (only() or defer()) only the fields loaded from the DB will get updated. In effect there is an automatic update_fields in this case. If you assign or change any deferred field value, the field will be added to the updated fields.

menghapus obyekLink to this heading

Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False)Link to this definition

Issues an SQL DELETE for the object. This only deletes the object in the database; the Python instance will still exist and will still have data in its fields. This method returns the number of objects deleted and a dictionary with the number of deletions per object type.

Untuk rincian lebih, termasuk bagaimana menghapus obyek-obyek dalam kumpulan, lihat menghapus obyek.

Jika anda ingin menyesuaikan perilaku hapus, anda dapat menimpa metode delete(). Lihat Menimpa metode model yang detetapkan untuk lebih rinci.

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.

Pickling objectsLink to this heading

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 methodsLink to this heading

A few object methods have special purposes.

__str__()Link to this heading

Model.__str__()Link to this definition

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.

Sebagai contoh:

Code
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)

__eq__()Link to this heading

Model.__eq__()Link to this definition

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.

Sebagai contoh:

Code
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)
# Primary 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__()Link to this heading

Model.__hash__()Link to this definition

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()Link to this heading

Model.get_absolute_url()Link to this definition

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.

Sebagai contoh:

Code
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.

Sebagai contoh:

Code
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().

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:

Django template
<!-- BAD template code. Avoid! -->
<a href="/people/{{ object.id }}/">{{ object.name }}</a>

Kode cetakan ini jauh lebih baik:

Django template
<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 small like correcting a spelling error, you don't want to have to track down every place that the URL might be created. Specify it once, in get_absolute_url() and have all your other code call that one place.

Extra instance methodsLink to this heading

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

Model.get_FOO_display()Link to this definition

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.

Sebagai contoh:

Code
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)
Code
>>> 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)Link to this definition
Model.get_previous_by_FOO(**kwargs)Link to this definition

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.

Atribut-atribut lainLink to this heading

_stateLink to this heading

Model._stateLink to this definition

The _state attribute refers to a ModelState object that tracks the lifecycle of the model instance.

The ModelState object has two attributes: adding, a flag which is True if the model has not been saved to the database yet, and db, a string referring to the database alias the instance was loaded from or saved to.

Newly instantiated instances have adding=True and db=None, since they are yet to be saved. Instances fetched from a QuerySet will have adding=False and db set to the alias of the associated database.