{"title":"Model instance reference","version":"5.1","locale":"es","docname":"ref/models/instances","url":"/es/5.1/ref/models/instances/","canonical":"https://djangodocs.dev/es/5.1/ref/models/instances/","summary":"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…","html":"<h1>Model instance reference<a class=\"heading-anchor\" href=\"#model-instance-reference\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>This document describes the details of the <code class=\"docutils literal notranslate\">Model</code> API. It builds on the\nmaterial presented in the <a class=\"reference internal\" href=\"/es/5.1/topics/db/models/\"><span class=\"doc\">model</span></a> and <a class=\"reference internal\" href=\"/es/5.1/topics/db/queries/\"><span class=\"doc\">database\nquery</span></a> guides, so you’ll probably want to read and\nunderstand those documents before reading this one.</p>\n<p>Throughout this reference we’ll use the <a class=\"reference internal\" href=\"/es/5.1/topics/db/queries/#queryset-model-example\"><span class=\"std std-ref\">example blog models</span></a> presented in the <a class=\"reference internal\" href=\"/es/5.1/topics/db/queries/\"><span class=\"doc\">database query guide</span></a>.</p>\n<section id=\"creating-objects\">\n<h2>Creating objects<a class=\"heading-anchor\" href=\"#creating-objects\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>To create a new instance of a model, instantiate it like any other Python\nclass:</p>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">Model</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">**</span>kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The keyword arguments are the names of the fields you’ve defined on your model.\nNote that instantiating a model in no way touches your database; for that, you\nneed to <a class=\"reference internal\" href=\"#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a>.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Nota</p>\n<p>You may be tempted to customize the model by overriding the <code class=\"docutils literal notranslate\">__init__</code>\nmethod. If you do so, however, take care not to change the calling\nsignature as any change may prevent the model instance from being saved.\nAdditionally, referring to model fields within <code class=\"docutils literal notranslate\">__init__</code> may potentially\nresult in infinite recursion errors in some circumstances.  Rather than\noverriding <code class=\"docutils literal notranslate\">__init__</code>, try using one of these approaches:</p>\n<ol class=\"arabic\">\n<li><p>Add a classmethod on the model class:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Book</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    title <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n\n    <span class=\"nd\">@classmethod</span>\n    <span class=\"k\">def</span> <span class=\"nf\">create</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">,</span> title<span class=\"p\">):</span>\n        book <span class=\"o\">=</span> <span class=\"bp\">cls</span><span class=\"p\">(</span>title<span class=\"o\">=</span>title<span class=\"p\">)</span>\n        <span class=\"c1\"># do something with the book</span>\n        <span class=\"k\">return</span> book\n\n\nbook <span class=\"o\">=</span> Book<span class=\"o\">.</span>create<span class=\"p\">(</span><span class=\"s2\">&quot;Pride and Prejudice&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n</li>\n<li><p>Add a method on a custom manager (usually preferred):</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">BookManager</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Manager<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">create_book</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> title<span class=\"p\">):</span>\n        book <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>create<span class=\"p\">(</span>title<span class=\"o\">=</span>title<span class=\"p\">)</span>\n        <span class=\"c1\"># do something with the book</span>\n        <span class=\"k\">return</span> book\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Book</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    title <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n\n    objects <span class=\"o\">=</span> BookManager<span class=\"p\">()</span>\n\n\nbook <span class=\"o\">=</span> Book<span class=\"o\">.</span>objects<span class=\"o\">.</span>create_book<span class=\"p\">(</span><span class=\"s2\">&quot;Pride and Prejudice&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n</li>\n</ol>\n</aside>\n<section id=\"customizing-model-loading\">\n<h3>Customizing model loading<a class=\"heading-anchor\" href=\"#customizing-model-loading\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.from_db\">\n<em class=\"property\"><span class=\"k\">classmethod</span> </em><span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">from_db</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">db</em>, <em class=\"sig-param\">field_names</em>, <em class=\"sig-param\">values</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.from_db\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The <code class=\"docutils literal notranslate\">from_db()</code> method can be used to customize model instance creation\nwhen loading from the database.</p>\n<p>The <code class=\"docutils literal notranslate\">db</code> argument contains the database alias for the database the model\nis loaded from, <code class=\"docutils literal notranslate\">field_names</code> contains the names of all loaded fields, and\n<code class=\"docutils literal notranslate\">values</code> contains the loaded values for each field in <code class=\"docutils literal notranslate\">field_names</code>. The\n<code class=\"docutils literal notranslate\">field_names</code> are in the same order as the <code class=\"docutils literal notranslate\">values</code>. If all of the model’s\nfields are present, then <code class=\"docutils literal notranslate\">values</code> are guaranteed to be in the order\n<code class=\"docutils literal notranslate\">__init__()</code> expects them. That is, the instance can be created by\n<code class=\"docutils literal notranslate\">cls(*values)</code>. If any fields are deferred, they won’t appear in\n<code class=\"docutils literal notranslate\">field_names</code>. In that case, assign a value of <code class=\"docutils literal notranslate\">django.db.models.DEFERRED</code>\nto each of the missing fields.</p>\n<p>In addition to creating the new model, the <code class=\"docutils literal notranslate\">from_db()</code> method must set the\n<code class=\"docutils literal notranslate\">adding</code> and <code class=\"docutils literal notranslate\">db</code> flags in the new instance’s <a class=\"reference internal\" href=\"#django.db.models.Model._state\" title=\"django.db.models.Model._state\"><code class=\"xref py py-attr docutils literal notranslate\">_state</code></a> attribute.</p>\n<p>Below is an example showing how to record the initial values of fields that\nare loaded from the database:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db.models</span> <span class=\"kn\">import</span> DEFERRED\n\n\n<span class=\"nd\">@classmethod</span>\n<span class=\"k\">def</span> <span class=\"nf\">from_db</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"p\">,</span> db<span class=\"p\">,</span> field_names<span class=\"p\">,</span> values<span class=\"p\">):</span>\n    <span class=\"c1\"># Default implementation of from_db() (subject to change and could</span>\n    <span class=\"c1\"># be replaced with super()).</span>\n    <span class=\"k\">if</span> <span class=\"nb\">len</span><span class=\"p\">(</span>values<span class=\"p\">)</span> <span class=\"o\">!=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"bp\">cls</span><span class=\"o\">.</span>_meta<span class=\"o\">.</span>concrete_fields<span class=\"p\">):</span>\n        values <span class=\"o\">=</span> <span class=\"nb\">list</span><span class=\"p\">(</span>values<span class=\"p\">)</span>\n        values<span class=\"o\">.</span>reverse<span class=\"p\">()</span>\n        values <span class=\"o\">=</span> <span class=\"p\">[</span>\n            values<span class=\"o\">.</span>pop<span class=\"p\">()</span> <span class=\"k\">if</span> f<span class=\"o\">.</span>attname <span class=\"ow\">in</span> field_names <span class=\"k\">else</span> DEFERRED\n            <span class=\"k\">for</span> f <span class=\"ow\">in</span> <span class=\"bp\">cls</span><span class=\"o\">.</span>_meta<span class=\"o\">.</span>concrete_fields\n        <span class=\"p\">]</span>\n    instance <span class=\"o\">=</span> <span class=\"bp\">cls</span><span class=\"p\">(</span><span class=\"o\">*</span>values<span class=\"p\">)</span>\n    instance<span class=\"o\">.</span>_state<span class=\"o\">.</span>adding <span class=\"o\">=</span> <span class=\"kc\">False</span>\n    instance<span class=\"o\">.</span>_state<span class=\"o\">.</span>db <span class=\"o\">=</span> db\n    <span class=\"c1\"># customization to store the original field values on the instance</span>\n    instance<span class=\"o\">.</span>_loaded_values <span class=\"o\">=</span> <span class=\"nb\">dict</span><span class=\"p\">(</span>\n        <span class=\"nb\">zip</span><span class=\"p\">(</span>field_names<span class=\"p\">,</span> <span class=\"p\">(</span>value <span class=\"k\">for</span> value <span class=\"ow\">in</span> values <span class=\"k\">if</span> value <span class=\"ow\">is</span> <span class=\"ow\">not</span> DEFERRED<span class=\"p\">))</span>\n    <span class=\"p\">)</span>\n    <span class=\"k\">return</span> instance\n\n\n<span class=\"k\">def</span> <span class=\"nf\">save</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">):</span>\n    <span class=\"c1\"># Check how the current values differ from ._loaded_values. For example,</span>\n    <span class=\"c1\"># prevent changing the creator_id of the model. (This example doesn&#39;t</span>\n    <span class=\"c1\"># support cases where &#39;creator_id&#39; is deferred).</span>\n    <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"bp\">self</span><span class=\"o\">.</span>_state<span class=\"o\">.</span>adding <span class=\"ow\">and</span> <span class=\"p\">(</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>creator_id <span class=\"o\">!=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>_loaded_values<span class=\"p\">[</span><span class=\"s2\">&quot;creator_id&quot;</span><span class=\"p\">]</span>\n    <span class=\"p\">):</span>\n        <span class=\"k\">raise</span> <span class=\"ne\">ValueError</span><span class=\"p\">(</span><span class=\"s2\">&quot;Updating the value of creator isn&#39;t allowed&quot;</span><span class=\"p\">)</span>\n    <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span>save<span class=\"p\">(</span><span class=\"o\">**</span>kwargs<span class=\"p\">)</span>\n</code></pre></div>\n<p>The example above shows a full <code class=\"docutils literal notranslate\">from_db()</code> implementation to clarify how that\nis done. In this case it would be possible to use a <code class=\"docutils literal notranslate\">super()</code> call in the\n<code class=\"docutils literal notranslate\">from_db()</code> method.</p>\n</section>\n</section>\n<section id=\"refreshing-objects-from-database\">\n<h2>Refreshing objects from database<a class=\"heading-anchor\" href=\"#refreshing-objects-from-database\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>If you delete a field from a model instance, accessing it again reloads the\nvalue from the database:</p>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>obj <span class=\"o\">=</span> MyModel<span class=\"o\">.</span>objects<span class=\"o\">.</span>first<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"k\">del</span> obj<span class=\"o\">.</span>field\n<span class=\"gp\">&gt;&gt;&gt; </span>obj<span class=\"o\">.</span>field  <span class=\"c1\"># Loads the field from the database</span>\n</code></pre></div>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.refresh_from_db\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">refresh_from_db</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">fields<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">from_queryset<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.refresh_from_db\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.arefresh_from_db\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">arefresh_from_db</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">fields<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">from_queryset<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.arefresh_from_db\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><em>Asynchronous version</em>: <code class=\"docutils literal notranslate\">arefresh_from_db()</code></p>\n<p>If you need to reload a model’s values from the database, you can use the\n<code class=\"docutils literal notranslate\">refresh_from_db()</code> method. When this method is called without arguments the\nfollowing is done:</p>\n<ol class=\"arabic simple\">\n<li><p>All non-deferred fields of the model are updated to the values currently\npresent in the database.</p></li>\n<li><p>Any cached relations are cleared from the reloaded instance.</p></li>\n</ol>\n<p>Only fields of the model are reloaded from the database. Other\ndatabase-dependent values such as annotations aren’t reloaded. Any\n<a class=\"reference internal\" href=\"/es/5.1/ref/utils/#django.utils.functional.cached_property\" title=\"django.utils.functional.cached_property\"><code class=\"xref py py-func docutils literal notranslate\">&#64;cached_property</code></a> attributes\naren’t cleared either.</p>\n<p>The reloading happens from the database the instance was loaded from, or from\nthe default database if the instance wasn’t loaded from the database. The\n<code class=\"docutils literal notranslate\">using</code> argument can be used to force the database used for reloading.</p>\n<p>It is possible to force the set of fields to be loaded by using the <code class=\"docutils literal notranslate\">fields</code>\nargument.</p>\n<p>For example, to test that an <code class=\"docutils literal notranslate\">update()</code> call resulted in the expected\nupdate, you could write a test similar to this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">test_update_result</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    obj <span class=\"o\">=</span> MyModel<span class=\"o\">.</span>objects<span class=\"o\">.</span>create<span class=\"p\">(</span>val<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n    MyModel<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>pk<span class=\"o\">=</span>obj<span class=\"o\">.</span>pk<span class=\"p\">)</span><span class=\"o\">.</span>update<span class=\"p\">(</span>val<span class=\"o\">=</span>F<span class=\"p\">(</span><span class=\"s2\">&quot;val&quot;</span><span class=\"p\">)</span> <span class=\"o\">+</span> <span class=\"mi\">1</span><span class=\"p\">)</span>\n    <span class=\"c1\"># At this point obj.val is still 1, but the value in the database</span>\n    <span class=\"c1\"># was updated to 2. The object&#39;s updated value needs to be reloaded</span>\n    <span class=\"c1\"># from the database.</span>\n    obj<span class=\"o\">.</span>refresh_from_db<span class=\"p\">()</span>\n    <span class=\"bp\">self</span><span class=\"o\">.</span>assertEqual<span class=\"p\">(</span>obj<span class=\"o\">.</span>val<span class=\"p\">,</span> <span class=\"mi\">2</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>Note that when deferred fields are accessed, the loading of the deferred\nfield’s value happens through this method. Thus it is possible to customize\nthe way deferred loading happens. The example below shows how one can reload\nall of the instance’s fields when a deferred field is reloaded:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">ExampleModel</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">refresh_from_db</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> using<span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">,</span> fields<span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">):</span>\n        <span class=\"c1\"># fields contains the name of the deferred field to be</span>\n        <span class=\"c1\"># loaded.</span>\n        <span class=\"k\">if</span> fields <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            fields <span class=\"o\">=</span> <span class=\"nb\">set</span><span class=\"p\">(</span>fields<span class=\"p\">)</span>\n            deferred_fields <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>get_deferred_fields<span class=\"p\">()</span>\n            <span class=\"c1\"># If any deferred field is going to be loaded</span>\n            <span class=\"k\">if</span> fields<span class=\"o\">.</span>intersection<span class=\"p\">(</span>deferred_fields<span class=\"p\">):</span>\n                <span class=\"c1\"># then load all of them</span>\n                fields <span class=\"o\">=</span> fields<span class=\"o\">.</span>union<span class=\"p\">(</span>deferred_fields<span class=\"p\">)</span>\n        <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span>refresh_from_db<span class=\"p\">(</span>using<span class=\"p\">,</span> fields<span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">)</span>\n</code></pre></div>\n<p>The <code class=\"docutils literal notranslate\">from_queryset</code> argument allows using a different queryset than the one\ncreated from <a class=\"reference internal\" href=\"/es/5.1/topics/db/managers/#django.db.models.Model._base_manager\" title=\"django.db.models.Model._base_manager\"><code class=\"xref py py-attr docutils literal notranslate\">_base_manager</code></a>. It gives you more\ncontrol over how the model is reloaded. For example, when your model uses soft\ndeletion you can make <code class=\"docutils literal notranslate\">refresh_from_db()</code> to take this into account:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>obj<span class=\"o\">.</span>refresh_from_db<span class=\"p\">(</span>from_queryset<span class=\"o\">=</span>MyModel<span class=\"o\">.</span>active_objects<span class=\"o\">.</span>all<span class=\"p\">())</span>\n</code></pre></div>\n<p>You can cache related objects that otherwise would be cleared from the reloaded\ninstance:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>obj<span class=\"o\">.</span>refresh_from_db<span class=\"p\">(</span>from_queryset<span class=\"o\">=</span>MyModel<span class=\"o\">.</span>objects<span class=\"o\">.</span>select_related<span class=\"p\">(</span><span class=\"s2\">&quot;related_field&quot;</span><span class=\"p\">))</span>\n</code></pre></div>\n<p>You can lock the row until the end of transaction before reloading a model’s\nvalues:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>obj<span class=\"o\">.</span>refresh_from_db<span class=\"p\">(</span>from_queryset<span class=\"o\">=</span>MyModel<span class=\"o\">.</span>objects<span class=\"o\">.</span>select_for_update<span class=\"p\">())</span>\n</code></pre></div>\n<aside class=\"version-note version-changed\" data-version=\"5.1\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 5.1</p><p>The <code class=\"docutils literal notranslate\">from_queryset</code> argument was added.</p>\n</aside>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.get_deferred_fields\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">get_deferred_fields</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.get_deferred_fields\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>A helper method that returns a set containing the attribute names of all those\nfields that are currently deferred for this model.</p>\n</section>\n<section id=\"validating-objects\">\n<span id=\"id1\"></span><h2>Validating objects<a class=\"heading-anchor\" href=\"#validating-objects\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>There are four steps involved in validating a model:</p>\n<ol class=\"arabic simple\">\n<li><p>Validate the model fields - <a class=\"reference internal\" href=\"#django.db.models.Model.clean_fields\" title=\"django.db.models.Model.clean_fields\"><code class=\"xref py py-meth docutils literal notranslate\">Model.clean_fields()</code></a></p></li>\n<li><p>Validate the model as a whole - <a class=\"reference internal\" href=\"#django.db.models.Model.clean\" title=\"django.db.models.Model.clean\"><code class=\"xref py py-meth docutils literal notranslate\">Model.clean()</code></a></p></li>\n<li><p>Validate the field uniqueness - <a class=\"reference internal\" href=\"#django.db.models.Model.validate_unique\" title=\"django.db.models.Model.validate_unique\"><code class=\"xref py py-meth docutils literal notranslate\">Model.validate_unique()</code></a></p></li>\n<li><p>Validate the constraints - <a class=\"reference internal\" href=\"#django.db.models.Model.validate_constraints\" title=\"django.db.models.Model.validate_constraints\"><code class=\"xref py py-meth docutils literal notranslate\">Model.validate_constraints()</code></a></p></li>\n</ol>\n<p>All four steps are performed when you call a model’s <a class=\"reference internal\" href=\"#django.db.models.Model.full_clean\" title=\"django.db.models.Model.full_clean\"><code class=\"xref py py-meth docutils literal notranslate\">full_clean()</code></a>\nmethod.</p>\n<p>When you use a <a class=\"reference internal\" href=\"/es/5.1/topics/forms/modelforms/#django.forms.ModelForm\" title=\"django.forms.ModelForm\"><code class=\"xref py py-class docutils literal notranslate\">ModelForm</code></a>, the call to\n<a class=\"reference internal\" href=\"/es/5.1/ref/forms/api/#django.forms.Form.is_valid\" title=\"django.forms.Form.is_valid\"><code class=\"xref py py-meth docutils literal notranslate\">is_valid()</code></a> will perform these validation steps for\nall the fields that are included on the form. See the <a class=\"reference internal\" href=\"/es/5.1/topics/forms/modelforms/\"><span class=\"doc\">ModelForm\ndocumentation</span></a> for more information. You should only\nneed to call a model’s <a class=\"reference internal\" href=\"#django.db.models.Model.full_clean\" title=\"django.db.models.Model.full_clean\"><code class=\"xref py py-meth docutils literal notranslate\">full_clean()</code></a> method if you plan to handle\nvalidation errors yourself, or if you have excluded fields from the\n<a class=\"reference internal\" href=\"/es/5.1/topics/forms/modelforms/#django.forms.ModelForm\" title=\"django.forms.ModelForm\"><code class=\"xref py py-class docutils literal notranslate\">ModelForm</code></a> that require validation.</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.full_clean\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">full_clean</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">exclude<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">validate_unique<span class=\"o\">=</span><span class=\"default_value\">True</span></em>, <em class=\"sig-param\">validate_constraints<span class=\"o\">=</span><span class=\"default_value\">True</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.full_clean\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>This method calls <a class=\"reference internal\" href=\"#django.db.models.Model.clean_fields\" title=\"django.db.models.Model.clean_fields\"><code class=\"xref py py-meth docutils literal notranslate\">Model.clean_fields()</code></a>, <a class=\"reference internal\" href=\"#django.db.models.Model.clean\" title=\"django.db.models.Model.clean\"><code class=\"xref py py-meth docutils literal notranslate\">Model.clean()</code></a>,\n<a class=\"reference internal\" href=\"#django.db.models.Model.validate_unique\" title=\"django.db.models.Model.validate_unique\"><code class=\"xref py py-meth docutils literal notranslate\">Model.validate_unique()</code></a> (if <code class=\"docutils literal notranslate\">validate_unique</code> is <code class=\"docutils literal notranslate\">True</code>),  and\n<a class=\"reference internal\" href=\"#django.db.models.Model.validate_constraints\" title=\"django.db.models.Model.validate_constraints\"><code class=\"xref py py-meth docutils literal notranslate\">Model.validate_constraints()</code></a> (if <code class=\"docutils literal notranslate\">validate_constraints</code> is <code class=\"docutils literal notranslate\">True</code>)\nin that order and raises a <a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a> that\nhas a <code class=\"docutils literal notranslate\">message_dict</code> attribute containing errors from all four stages.</p>\n<p>The optional <code class=\"docutils literal notranslate\">exclude</code> argument can be used to provide a <code class=\"docutils literal notranslate\">set</code> of field\nnames that can be excluded from validation and cleaning.\n<a class=\"reference internal\" href=\"/es/5.1/topics/forms/modelforms/#django.forms.ModelForm\" title=\"django.forms.ModelForm\"><code class=\"xref py py-class docutils literal notranslate\">ModelForm</code></a> uses this argument to exclude fields that\naren’t present on your form from being validated since any errors raised could\nnot be corrected by the user.</p>\n<p>Note that <code class=\"docutils literal notranslate\">full_clean()</code> will <em>not</em> be called automatically when you call\nyour model’s <a class=\"reference internal\" href=\"#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a> method. You’ll need to call it manually\nwhen you want to run one-step model validation for your own manually created\nmodels. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.core.exceptions</span> <span class=\"kn\">import</span> ValidationError\n\n<span class=\"k\">try</span><span class=\"p\">:</span>\n    article<span class=\"o\">.</span>full_clean<span class=\"p\">()</span>\n<span class=\"k\">except</span> ValidationError <span class=\"k\">as</span> e<span class=\"p\">:</span>\n    <span class=\"c1\"># Do something based on the errors contained in e.message_dict.</span>\n    <span class=\"c1\"># Display them to a user, or handle them programmatically.</span>\n    <span class=\"k\">pass</span>\n</code></pre></div>\n<p>The first step <code class=\"docutils literal notranslate\">full_clean()</code> performs is to clean each individual field.</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.clean_fields\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">clean_fields</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">exclude<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.clean_fields\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>This method will validate all fields on your model. The optional <code class=\"docutils literal notranslate\">exclude</code>\nargument lets you provide a <code class=\"docutils literal notranslate\">set</code> of field names to exclude from validation.\nIt will raise a <a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a> if any fields\nfail validation.</p>\n<p>The second step <code class=\"docutils literal notranslate\">full_clean()</code> performs is to call <a class=\"reference internal\" href=\"#django.db.models.Model.clean\" title=\"django.db.models.Model.clean\"><code class=\"xref py py-meth docutils literal notranslate\">Model.clean()</code></a>.\nThis method should be overridden to perform custom validation on your model.</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.clean\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">clean</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.clean\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>This method should be used to provide custom model validation, and to modify\nattributes on your model if desired. For instance, you could use it to\nautomatically provide a value for a field, or to do validation that requires\naccess to more than a single field:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">import</span> <span class=\"nn\">datetime</span>\n<span class=\"kn\">from</span> <span class=\"nn\">django.core.exceptions</span> <span class=\"kn\">import</span> ValidationError\n<span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n<span class=\"kn\">from</span> <span class=\"nn\">django.utils.translation</span> <span class=\"kn\">import</span> gettext_lazy <span class=\"k\">as</span> _\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Article</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">clean</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Don&#39;t allow draft entries to have a pub_date.</span>\n        <span class=\"k\">if</span> <span class=\"bp\">self</span><span class=\"o\">.</span>status <span class=\"o\">==</span> <span class=\"s2\">&quot;draft&quot;</span> <span class=\"ow\">and</span> <span class=\"bp\">self</span><span class=\"o\">.</span>pub_date <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            <span class=\"k\">raise</span> ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s2\">&quot;Draft entries may not have a publication date.&quot;</span><span class=\"p\">))</span>\n        <span class=\"c1\"># Set the pub_date for published items if it hasn&#39;t been set already.</span>\n        <span class=\"k\">if</span> <span class=\"bp\">self</span><span class=\"o\">.</span>status <span class=\"o\">==</span> <span class=\"s2\">&quot;published&quot;</span> <span class=\"ow\">and</span> <span class=\"bp\">self</span><span class=\"o\">.</span>pub_date <span class=\"ow\">is</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            <span class=\"bp\">self</span><span class=\"o\">.</span>pub_date <span class=\"o\">=</span> datetime<span class=\"o\">.</span>date<span class=\"o\">.</span>today<span class=\"p\">()</span>\n</code></pre></div>\n<p>Note, however, that like <a class=\"reference internal\" href=\"#django.db.models.Model.full_clean\" title=\"django.db.models.Model.full_clean\"><code class=\"xref py py-meth docutils literal notranslate\">Model.full_clean()</code></a>, a model’s <code class=\"docutils literal notranslate\">clean()</code>\nmethod is not invoked when you call your model’s <a class=\"reference internal\" href=\"#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a> method.</p>\n<p>In the above example, the <a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a>\nexception raised by <code class=\"docutils literal notranslate\">Model.clean()</code> was instantiated with a string, so it\nwill be stored in a special error dictionary key,\n<a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.NON_FIELD_ERRORS\" title=\"django.core.exceptions.NON_FIELD_ERRORS\"><code class=\"xref py py-data docutils literal notranslate\">NON_FIELD_ERRORS</code></a>. This key is used for errors\nthat are tied to the entire model instead of to a specific field:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.core.exceptions</span> <span class=\"kn\">import</span> NON_FIELD_ERRORS<span class=\"p\">,</span> ValidationError\n\n<span class=\"k\">try</span><span class=\"p\">:</span>\n    article<span class=\"o\">.</span>full_clean<span class=\"p\">()</span>\n<span class=\"k\">except</span> ValidationError <span class=\"k\">as</span> e<span class=\"p\">:</span>\n    non_field_errors <span class=\"o\">=</span> e<span class=\"o\">.</span>message_dict<span class=\"p\">[</span>NON_FIELD_ERRORS<span class=\"p\">]</span>\n</code></pre></div>\n<p>To assign exceptions to a specific field, instantiate the\n<a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a> with a dictionary, where the\nkeys are the field names. We could update the previous example to assign the\nerror to the <code class=\"docutils literal notranslate\">pub_date</code> field:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Article</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">clean</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"c1\"># Don&#39;t allow draft entries to have a pub_date.</span>\n        <span class=\"k\">if</span> <span class=\"bp\">self</span><span class=\"o\">.</span>status <span class=\"o\">==</span> <span class=\"s2\">&quot;draft&quot;</span> <span class=\"ow\">and</span> <span class=\"bp\">self</span><span class=\"o\">.</span>pub_date <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            <span class=\"k\">raise</span> ValidationError<span class=\"p\">(</span>\n                <span class=\"p\">{</span><span class=\"s2\">&quot;pub_date&quot;</span><span class=\"p\">:</span> _<span class=\"p\">(</span><span class=\"s2\">&quot;Draft entries may not have a publication date.&quot;</span><span class=\"p\">)}</span>\n            <span class=\"p\">)</span>\n        <span class=\"o\">...</span>\n</code></pre></div>\n<p>If you detect errors in multiple fields during <code class=\"docutils literal notranslate\">Model.clean()</code>, you can also\npass a dictionary mapping field names to errors:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">raise</span> ValidationError<span class=\"p\">(</span>\n    <span class=\"p\">{</span>\n        <span class=\"s2\">&quot;title&quot;</span><span class=\"p\">:</span> ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s2\">&quot;Missing title.&quot;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s2\">&quot;required&quot;</span><span class=\"p\">),</span>\n        <span class=\"s2\">&quot;pub_date&quot;</span><span class=\"p\">:</span> ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s2\">&quot;Invalid date.&quot;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s2\">&quot;invalid&quot;</span><span class=\"p\">),</span>\n    <span class=\"p\">}</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p>Then, <code class=\"docutils literal notranslate\">full_clean()</code> will check unique constraints on your model.</p>\n<aside class=\"admonition-how-to-raise-field-specific-validation-errors-if-those-fields-don-t-appear-in-a-modelform admonition\" role=\"note\">\n<p class=\"admonition-title\">How to raise field-specific validation errors if those fields don’t appear in a <code class=\"docutils literal notranslate\">ModelForm</code></p>\n<p>You can’t raise validation errors in <code class=\"docutils literal notranslate\">Model.clean()</code> for fields that\ndon’t appear in a model form (a form may limit its fields using\n<code class=\"docutils literal notranslate\">Meta.fields</code> or <code class=\"docutils literal notranslate\">Meta.exclude</code>). Doing so will raise a <code class=\"docutils literal notranslate\">ValueError</code>\nbecause the validation error won’t be able to be associated with the\nexcluded field.</p>\n<p>To work around this dilemma, instead override <a class=\"reference internal\" href=\"#django.db.models.Model.clean_fields\" title=\"django.db.models.Model.clean_fields\"><code class=\"xref py py-meth docutils literal notranslate\">Model.clean_fields()</code></a> as it receives the list of fields\nthat are excluded from validation. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">Article</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">clean_fields</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> exclude<span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">):</span>\n        <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span>clean_fields<span class=\"p\">(</span>exclude<span class=\"o\">=</span>exclude<span class=\"p\">)</span>\n        <span class=\"k\">if</span> <span class=\"bp\">self</span><span class=\"o\">.</span>status <span class=\"o\">==</span> <span class=\"s2\">&quot;draft&quot;</span> <span class=\"ow\">and</span> <span class=\"bp\">self</span><span class=\"o\">.</span>pub_date <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            <span class=\"k\">if</span> exclude <span class=\"ow\">and</span> <span class=\"s2\">&quot;status&quot;</span> <span class=\"ow\">in</span> exclude<span class=\"p\">:</span>\n                <span class=\"k\">raise</span> ValidationError<span class=\"p\">(</span>\n                    _<span class=\"p\">(</span><span class=\"s2\">&quot;Draft entries may not have a publication date.&quot;</span><span class=\"p\">)</span>\n                <span class=\"p\">)</span>\n            <span class=\"k\">else</span><span class=\"p\">:</span>\n                <span class=\"k\">raise</span> ValidationError<span class=\"p\">(</span>\n                    <span class=\"p\">{</span>\n                        <span class=\"s2\">&quot;status&quot;</span><span class=\"p\">:</span> _<span class=\"p\">(</span>\n                            <span class=\"s2\">&quot;Set status to draft if there is not a publication date.&quot;</span>\n                        <span class=\"p\">),</span>\n                    <span class=\"p\">}</span>\n                <span class=\"p\">)</span>\n</code></pre></div>\n</aside>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.validate_unique\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">validate_unique</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">exclude<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.validate_unique\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>This method is similar to <a class=\"reference internal\" href=\"#django.db.models.Model.clean_fields\" title=\"django.db.models.Model.clean_fields\"><code class=\"xref py py-meth docutils literal notranslate\">clean_fields()</code></a>, but validates\nuniqueness constraints defined via <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.unique\" title=\"django.db.models.Field.unique\"><code class=\"xref py py-attr docutils literal notranslate\">Field.unique</code></a>,\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.unique_for_date\" title=\"django.db.models.Field.unique_for_date\"><code class=\"xref py py-attr docutils literal notranslate\">Field.unique_for_date</code></a>, <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.unique_for_month\" title=\"django.db.models.Field.unique_for_month\"><code class=\"xref py py-attr docutils literal notranslate\">Field.unique_for_month</code></a>,\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.unique_for_year\" title=\"django.db.models.Field.unique_for_year\"><code class=\"xref py py-attr docutils literal notranslate\">Field.unique_for_year</code></a>, or <a class=\"reference internal\" href=\"/es/5.1/ref/models/options/#django.db.models.Options.unique_together\" title=\"django.db.models.Options.unique_together\"><code class=\"xref py py-attr docutils literal notranslate\">Meta.unique_together</code></a> on your model instead of individual\nfield values. The optional <code class=\"docutils literal notranslate\">exclude</code> argument allows you to provide a <code class=\"docutils literal notranslate\">set</code>\nof field names to exclude from validation. It will raise a\n<a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a> if any fields fail validation.</p>\n<p><a class=\"reference internal\" href=\"/es/5.1/ref/models/constraints/#django.db.models.UniqueConstraint\" title=\"django.db.models.UniqueConstraint\"><code class=\"xref py py-class docutils literal notranslate\">UniqueConstraint</code></a>s defined in the\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/options/#django.db.models.Options.constraints\" title=\"django.db.models.Options.constraints\"><code class=\"xref py py-attr docutils literal notranslate\">Meta.constraints</code></a> are validated\nby <a class=\"reference internal\" href=\"#django.db.models.Model.validate_constraints\" title=\"django.db.models.Model.validate_constraints\"><code class=\"xref py py-meth docutils literal notranslate\">Model.validate_constraints()</code></a>.</p>\n<p>Note that if you provide an <code class=\"docutils literal notranslate\">exclude</code> argument to <code class=\"docutils literal notranslate\">validate_unique()</code>, any\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/options/#django.db.models.Options.unique_together\" title=\"django.db.models.Options.unique_together\"><code class=\"xref py py-attr docutils literal notranslate\">unique_together</code></a> constraint involving one of\nthe fields you provided will not be checked.</p>\n<p>Finally, <code class=\"docutils literal notranslate\">full_clean()</code> will check any other constraints on your model.</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.validate_constraints\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">validate_constraints</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">exclude<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.validate_constraints\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>This method validates all constraints defined in\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/options/#django.db.models.Options.constraints\" title=\"django.db.models.Options.constraints\"><code class=\"xref py py-attr docutils literal notranslate\">Meta.constraints</code></a>. The\noptional <code class=\"docutils literal notranslate\">exclude</code> argument allows you to provide a <code class=\"docutils literal notranslate\">set</code> of field names to\nexclude from validation. It will raise a\n<a class=\"reference internal\" href=\"/es/5.1/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a> if any constraints fail\nvalidation.</p>\n</section>\n<section id=\"saving-objects\">\n<h2>Saving objects<a class=\"heading-anchor\" href=\"#saving-objects\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>To save an object back to the database, call <code class=\"docutils literal notranslate\">save()</code>:</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.save\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">save</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"keyword-only-separator o\"><abbr title=\"Keyword-only parameters separator (PEP 3102)\">*</abbr></span></em>, <em class=\"sig-param\">force_insert<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">force_update<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">DEFAULT_DB_ALIAS</span></em>, <em class=\"sig-param\">update_fields<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.save\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.asave\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">asave</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"keyword-only-separator o\"><abbr title=\"Keyword-only parameters separator (PEP 3102)\">*</abbr></span></em>, <em class=\"sig-param\">force_insert<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">force_update<span class=\"o\">=</span><span class=\"default_value\">False</span></em>, <em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">DEFAULT_DB_ALIAS</span></em>, <em class=\"sig-param\">update_fields<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.asave\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><em>Asynchronous version</em>: <code class=\"docutils literal notranslate\">asave()</code></p>\n<p>For details on using the <code class=\"docutils literal notranslate\">force_insert</code> and <code class=\"docutils literal notranslate\">force_update</code> arguments, see\n<a class=\"reference internal\" href=\"#ref-models-force-insert\"><span class=\"std std-ref\">Forcing an INSERT or UPDATE</span></a>. Details about the <code class=\"docutils literal notranslate\">update_fields</code> argument\ncan be found in the <a class=\"reference internal\" href=\"#ref-models-update-fields\"><span class=\"std std-ref\">Specifying which fields to save</span></a> section.</p>\n<p>If you want customized saving behavior, you can override this <code class=\"docutils literal notranslate\">save()</code>\nmethod. See <a class=\"reference internal\" href=\"/es/5.1/topics/db/models/#overriding-model-methods\"><span class=\"std std-ref\">Overriding predefined model methods</span></a> for more details.</p>\n<p>The model save process also has some subtleties; see the sections below.</p>\n<aside class=\"version-note version-deprecated\" data-version=\"5.1\" role=\"note\">\n<p class=\"version-note-title\">Deprecated since Django 5.1</p><p><span class=\"versionmodified deprecated\">Obsoleto desde la versión 5.1: </span>Support for positional arguments is deprecated.</p>\n</aside>\n<section id=\"auto-incrementing-primary-keys\">\n<h3>Auto-incrementing primary keys<a class=\"heading-anchor\" href=\"#auto-incrementing-primary-keys\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If a model has an <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.AutoField\" title=\"django.db.models.AutoField\"><code class=\"xref py py-class docutils literal notranslate\">AutoField</code></a> — an auto-incrementing\nprimary key — then that auto-incremented value will be calculated and saved as\nan attribute on your object the first time you call <code class=\"docutils literal notranslate\">save()</code>:</p>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>b2 <span class=\"o\">=</span> Blog<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Cheddar Talk&quot;</span><span class=\"p\">,</span> tagline<span class=\"o\">=</span><span class=\"s2\">&quot;Thoughts on cheese.&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>b2<span class=\"o\">.</span>id  <span class=\"c1\"># Returns None, because b2 doesn&#39;t have an ID yet.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>b2<span class=\"o\">.</span>save<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>b2<span class=\"o\">.</span>id  <span class=\"c1\"># Returns the ID of your new object.</span>\n</code></pre></div>\n<p>There’s no way to tell what the value of an ID will be before you call\n<code class=\"docutils literal notranslate\">save()</code>, because that value is calculated by your database, not by Django.</p>\n<p>For convenience, each model has an <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.AutoField\" title=\"django.db.models.AutoField\"><code class=\"xref py py-class docutils literal notranslate\">AutoField</code></a> named\n<code class=\"docutils literal notranslate\">id</code> by default unless you explicitly specify <code class=\"docutils literal notranslate\">primary_key=True</code> on a field\nin your model. See the documentation for <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.AutoField\" title=\"django.db.models.AutoField\"><code class=\"xref py py-class docutils literal notranslate\">AutoField</code></a>\nfor more details.</p>\n<section id=\"the-pk-property\">\n<h4>The <code class=\"docutils literal notranslate\">pk</code> property<a class=\"heading-anchor\" href=\"#the-pk-property\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.pk\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">pk</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.pk\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Regardless of whether you define a primary key field yourself, or let Django\nsupply one for you, each model will have a property called <code class=\"docutils literal notranslate\">pk</code>. It behaves\nlike a normal attribute on the model, but is actually an alias for whichever\nattribute is the primary key field for the model. You can read and set this\nvalue, just as you would for any other attribute, and it will update the\ncorrect field in the model.</p>\n</section>\n<section id=\"explicitly-specifying-auto-primary-key-values\">\n<h4>Explicitly specifying auto-primary-key values<a class=\"heading-anchor\" href=\"#explicitly-specifying-auto-primary-key-values\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>If a model has an <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.AutoField\" title=\"django.db.models.AutoField\"><code class=\"xref py py-class docutils literal notranslate\">AutoField</code></a> but you want to define a\nnew object’s ID explicitly when saving, define it explicitly before saving,\nrather than relying on the auto-assignment of the ID:</p>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>b3 <span class=\"o\">=</span> Blog<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">3</span><span class=\"p\">,</span> name<span class=\"o\">=</span><span class=\"s2\">&quot;Cheddar Talk&quot;</span><span class=\"p\">,</span> tagline<span class=\"o\">=</span><span class=\"s2\">&quot;Thoughts on cheese.&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>b3<span class=\"o\">.</span>id  <span class=\"c1\"># Returns 3.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>b3<span class=\"o\">.</span>save<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>b3<span class=\"o\">.</span>id  <span class=\"c1\"># Returns 3.</span>\n</code></pre></div>\n<p>If you assign auto-primary-key values manually, make sure not to use an\nalready-existing primary-key value! If you create a new object with an explicit\nprimary-key value that already exists in the database, Django will assume you’re\nchanging the existing record rather than creating a new one.</p>\n<p>Given the above <code class=\"docutils literal notranslate\">'Cheddar Talk'</code> blog example, this example would override the\nprevious record in the database:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>b4 <span class=\"o\">=</span> Blog<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">3</span><span class=\"p\">,</span> name<span class=\"o\">=</span><span class=\"s2\">&quot;Not Cheddar&quot;</span><span class=\"p\">,</span> tagline<span class=\"o\">=</span><span class=\"s2\">&quot;Anything but cheese.&quot;</span><span class=\"p\">)</span>\nb4<span class=\"o\">.</span>save<span class=\"p\">()</span>  <span class=\"c1\"># Overrides the previous blog with ID=3!</span>\n</code></pre></div>\n<p>See <a class=\"reference internal\" href=\"#how-django-knows-to-update-vs-insert\">How Django knows to UPDATE vs. INSERT</a>, below, for the reason this\nhappens.</p>\n<p>Explicitly specifying auto-primary-key values is mostly useful for bulk-saving\nobjects, when you’re confident you won’t have primary-key collision.</p>\n<p>If you’re using PostgreSQL, the sequence associated with the primary key might\nneed to be updated; see <a class=\"reference internal\" href=\"/es/5.1/ref/databases/#manually-specified-autoincrement-pk\"><span class=\"std std-ref\">Manually-specifying values of auto-incrementing primary keys</span></a>.</p>\n</section>\n</section>\n<section id=\"what-happens-when-you-save\">\n<h3>What happens when you save?<a class=\"heading-anchor\" href=\"#what-happens-when-you-save\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When you save an object, Django performs the following steps:</p>\n<ol class=\"arabic\">\n<li><p><strong>Emit a pre-save signal.</strong> The <a class=\"reference internal\" href=\"/es/5.1/ref/signals/#django.db.models.signals.pre_save\" title=\"django.db.models.signals.pre_save\"><code class=\"xref py py-data docutils literal notranslate\">pre_save</code></a>\nsignal is sent, allowing any functions listening for that signal to do\nsomething.</p></li>\n<li><p><strong>Preprocess the data.</strong> Each field’s\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.pre_save\" title=\"django.db.models.Field.pre_save\"><code class=\"xref py py-meth docutils literal notranslate\">pre_save()</code></a> method is called to perform any\nautomated data modification that’s needed. For example, the date/time fields\noverride <code class=\"docutils literal notranslate\">pre_save()</code> to implement\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.DateField.auto_now_add\" title=\"django.db.models.DateField.auto_now_add\"><code class=\"xref py py-attr docutils literal notranslate\">auto_now_add</code></a> and\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.DateField.auto_now\" title=\"django.db.models.DateField.auto_now\"><code class=\"xref py py-attr docutils literal notranslate\">auto_now</code></a>.</p></li>\n<li><p><strong>Prepare the data for the database.</strong> Each field’s\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.get_db_prep_save\" title=\"django.db.models.Field.get_db_prep_save\"><code class=\"xref py py-meth docutils literal notranslate\">get_db_prep_save()</code></a> method is asked to provide\nits current value in a data type that can be written to the database.</p>\n<p>Most fields don’t require data preparation. Simple data types, such as\nintegers and strings, are “ready to write” as a Python object. However, more\ncomplex data types often require some modification.</p>\n<p>For example, <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.DateField\" title=\"django.db.models.DateField\"><code class=\"xref py py-class docutils literal notranslate\">DateField</code></a> fields use a Python\n<code class=\"docutils literal notranslate\">datetime</code> object to store data. Databases don’t store <code class=\"docutils literal notranslate\">datetime</code>\nobjects, so the field value must be converted into an ISO-compliant date\nstring for insertion into the database.</p>\n</li>\n<li><p><strong>Insert the data into the database.</strong> The preprocessed, prepared data is\ncomposed into an SQL statement for insertion into the database.</p></li>\n<li><p><strong>Emit a post-save signal.</strong> The <a class=\"reference internal\" href=\"/es/5.1/ref/signals/#django.db.models.signals.post_save\" title=\"django.db.models.signals.post_save\"><code class=\"xref py py-data docutils literal notranslate\">post_save</code></a>\nsignal is sent, allowing any functions listening for that signal to do\nsomething.</p></li>\n</ol>\n</section>\n<section id=\"how-django-knows-to-update-vs-insert\">\n<h3>How Django knows to UPDATE vs. INSERT<a class=\"heading-anchor\" href=\"#how-django-knows-to-update-vs-insert\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>You may have noticed Django database objects use the same <code class=\"docutils literal notranslate\">save()</code> method\nfor creating and changing objects. Django abstracts the need to use <code class=\"docutils literal notranslate\">INSERT</code>\nor <code class=\"docutils literal notranslate\">UPDATE</code> SQL statements. Specifically, when you call <code class=\"docutils literal notranslate\">save()</code> and the\nobject’s primary key attribute does <strong>not</strong> define a\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.default\" title=\"django.db.models.Field.default\"><code class=\"xref py py-attr docutils literal notranslate\">default</code></a> or\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.db_default\" title=\"django.db.models.Field.db_default\"><code class=\"xref py py-attr docutils literal notranslate\">db_default</code></a>, Django follows this algorithm:</p>\n<ul class=\"simple\">\n<li><p>If the object’s primary key attribute is set to anything except <code class=\"docutils literal notranslate\">None</code>,\nDjango executes an <code class=\"docutils literal notranslate\">UPDATE</code>.</p></li>\n<li><p>If the object’s primary key attribute is <em>not</em> set or if the <code class=\"docutils literal notranslate\">UPDATE</code>\ndidn’t update anything (e.g. if primary key is set to a value that doesn’t\nexist in the database), Django executes an <code class=\"docutils literal notranslate\">INSERT</code>.</p></li>\n</ul>\n<p>If the object’s primary key attribute defines a\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.default\" title=\"django.db.models.Field.default\"><code class=\"xref py py-attr docutils literal notranslate\">default</code></a> or\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.db_default\" title=\"django.db.models.Field.db_default\"><code class=\"xref py py-attr docutils literal notranslate\">db_default</code></a> then Django executes an <code class=\"docutils literal notranslate\">UPDATE</code>\nif it is an existing model instance and primary key is set to a value that\nexists in the database. Otherwise, Django executes an <code class=\"docutils literal notranslate\">INSERT</code>.</p>\n<p>The one gotcha here is that you should be careful not to specify a primary-key\nvalue explicitly when saving new objects, if you cannot guarantee the\nprimary-key value is unused. For more on this nuance, see <a class=\"reference internal\" href=\"#explicitly-specifying-auto-primary-key-values\">Explicitly specifying\nauto-primary-key values</a> above and <a class=\"reference internal\" href=\"#forcing-an-insert-or-update\">Forcing an INSERT or UPDATE</a> below.</p>\n<p>In Django 1.5 and earlier, Django did a <code class=\"docutils literal notranslate\">SELECT</code> when the primary key\nattribute was set. If the <code class=\"docutils literal notranslate\">SELECT</code> found a row, then Django did an <code class=\"docutils literal notranslate\">UPDATE</code>,\notherwise it did an <code class=\"docutils literal notranslate\">INSERT</code>. The old algorithm results in one more query in\nthe <code class=\"docutils literal notranslate\">UPDATE</code> case. There are some rare cases where the database doesn’t\nreport that a row was updated even if the database contains a row for the\nobject’s primary key value. An example is the PostgreSQL <code class=\"docutils literal notranslate\">ON UPDATE</code> trigger\nwhich returns <code class=\"docutils literal notranslate\">NULL</code>. In such cases it is possible to revert to the old\nalgorithm by setting the <a class=\"reference internal\" href=\"/es/5.1/ref/models/options/#django.db.models.Options.select_on_save\" title=\"django.db.models.Options.select_on_save\"><code class=\"xref py py-attr docutils literal notranslate\">select_on_save</code></a>\noption to <code class=\"docutils literal notranslate\">True</code>.</p>\n<aside class=\"version-note version-changed\" data-version=\"5.0\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 5.0</p><p>The <code class=\"docutils literal notranslate\">Field.db_default</code> parameter was added.</p>\n</aside>\n<section id=\"forcing-an-insert-or-update\">\n<span id=\"ref-models-force-insert\"></span><h4>Forcing an INSERT or UPDATE<a class=\"heading-anchor\" href=\"#forcing-an-insert-or-update\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>In some rare circumstances, it’s necessary to be able to force the\n<a class=\"reference internal\" href=\"#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a> method to perform an SQL <code class=\"docutils literal notranslate\">INSERT</code> and not fall back to\ndoing an <code class=\"docutils literal notranslate\">UPDATE</code>. Or vice-versa: update, if possible, but not insert a new\nrow. In these cases you can pass the <code class=\"docutils literal notranslate\">force_insert=True</code> or\n<code class=\"docutils literal notranslate\">force_update=True</code> parameters to the <a class=\"reference internal\" href=\"#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a> method.\nPassing both parameters is an error: you cannot both insert <em>and</em> update at the\nsame time!</p>\n<p>When using <a class=\"reference internal\" href=\"/es/5.1/topics/db/models/#multi-table-inheritance\"><span class=\"std std-ref\">multi-table inheritance</span></a>, it’s also\npossible to provide a tuple of parent classes to <code class=\"docutils literal notranslate\">force_insert</code> in order to\nforce <code class=\"docutils literal notranslate\">INSERT</code> statements for each base. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>Restaurant<span class=\"p\">(</span>pk<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">,</span> name<span class=\"o\">=</span><span class=\"s2\">&quot;Bob&#39;s Cafe&quot;</span><span class=\"p\">)</span><span class=\"o\">.</span>save<span class=\"p\">(</span>force_insert<span class=\"o\">=</span><span class=\"p\">(</span>Place<span class=\"p\">,))</span>\n\nRestaurant<span class=\"p\">(</span>pk<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">,</span> name<span class=\"o\">=</span><span class=\"s2\">&quot;Bob&#39;s Cafe&quot;</span><span class=\"p\">,</span> rating<span class=\"o\">=</span><span class=\"mi\">4</span><span class=\"p\">)</span><span class=\"o\">.</span>save<span class=\"p\">(</span>force_insert<span class=\"o\">=</span><span class=\"p\">(</span>Place<span class=\"p\">,</span> Rating<span class=\"p\">))</span>\n</code></pre></div>\n<p>You can pass <code class=\"docutils literal notranslate\">force_insert=(models.Model,)</code> to force an <code class=\"docutils literal notranslate\">INSERT</code> statement\nfor all parents. By default, <code class=\"docutils literal notranslate\">force_insert=True</code> only forces the insertion of\na new row for the current model.</p>\n<p>It should be very rare that you’ll need to use these parameters. Django will\nalmost always do the right thing and trying to override that will lead to\nerrors that are difficult to track down. This feature is for advanced use\nonly.</p>\n<p>Using <code class=\"docutils literal notranslate\">update_fields</code> will force an update similarly to <code class=\"docutils literal notranslate\">force_update</code>.</p>\n<aside class=\"version-note version-changed\" data-version=\"5.0\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 5.0</p><p>Support for passing a tuple of parent classes to <code class=\"docutils literal notranslate\">force_insert</code> was\nadded.</p>\n</aside>\n</section>\n</section>\n<section id=\"updating-attributes-based-on-existing-fields\">\n<span id=\"ref-models-field-updates-using-f-expressions\"></span><h3>Updating attributes based on existing fields<a class=\"heading-anchor\" href=\"#updating-attributes-based-on-existing-fields\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Sometimes you’ll need to perform a simple arithmetic task on a field, such\nas incrementing or decrementing the current value. One way of achieving this is\ndoing the arithmetic in Python like:</p>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>product <span class=\"o\">=</span> Product<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Venezuelan Beaver Cheese&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>product<span class=\"o\">.</span>number_sold <span class=\"o\">+=</span> <span class=\"mi\">1</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>product<span class=\"o\">.</span>save<span class=\"p\">()</span>\n</code></pre></div>\n<p>If the old <code class=\"docutils literal notranslate\">number_sold</code> value retrieved from the database was 10, then\nthe value of 11 will be written back to the database.</p>\n<p>The process can be made robust, <a class=\"reference internal\" href=\"/es/5.1/ref/models/expressions/#avoiding-race-conditions-using-f\"><span class=\"std std-ref\">avoiding a race condition</span></a>, as well as slightly faster by expressing\nthe update relative to the original field value, rather than as an explicit\nassignment of a new value. Django provides <a class=\"reference internal\" href=\"/es/5.1/ref/models/expressions/#django.db.models.F\" title=\"django.db.models.F\"><code class=\"xref py py-class docutils literal notranslate\">F expressions</code></a> for performing this kind of relative update. Using\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/expressions/#django.db.models.F\" title=\"django.db.models.F\"><code class=\"xref py py-class docutils literal notranslate\">F expressions</code></a>, the previous example is expressed\nas:</p>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">django.db.models</span> <span class=\"kn\">import</span> F\n<span class=\"gp\">&gt;&gt;&gt; </span>product <span class=\"o\">=</span> Product<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Venezuelan Beaver Cheese&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>product<span class=\"o\">.</span>number_sold <span class=\"o\">=</span> F<span class=\"p\">(</span><span class=\"s2\">&quot;number_sold&quot;</span><span class=\"p\">)</span> <span class=\"o\">+</span> <span class=\"mi\">1</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>product<span class=\"o\">.</span>save<span class=\"p\">()</span>\n</code></pre></div>\n<p>For more details, see the documentation on <a class=\"reference internal\" href=\"/es/5.1/ref/models/expressions/#django.db.models.F\" title=\"django.db.models.F\"><code class=\"xref py py-class docutils literal notranslate\">F expressions</code></a> and their <a class=\"reference internal\" href=\"/es/5.1/topics/db/queries/#topics-db-queries-update\"><span class=\"std std-ref\">use in update queries</span></a>.</p>\n</section>\n<section id=\"specifying-which-fields-to-save\">\n<span id=\"ref-models-update-fields\"></span><h3>Specifying which fields to save<a class=\"heading-anchor\" href=\"#specifying-which-fields-to-save\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If <code class=\"docutils literal notranslate\">save()</code> is passed a list of field names in keyword argument\n<code class=\"docutils literal notranslate\">update_fields</code>, only the fields named in that list will be updated.\nThis may be desirable if you want to update just one or a few fields on\nan object. There will be a slight performance benefit from preventing\nall of the model fields from being updated in the database. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>product<span class=\"o\">.</span>name <span class=\"o\">=</span> <span class=\"s2\">&quot;Name changed again&quot;</span>\nproduct<span class=\"o\">.</span>save<span class=\"p\">(</span>update_fields<span class=\"o\">=</span><span class=\"p\">[</span><span class=\"s2\">&quot;name&quot;</span><span class=\"p\">])</span>\n</code></pre></div>\n<p>The <code class=\"docutils literal notranslate\">update_fields</code> argument can be any iterable containing strings. An\nempty <code class=\"docutils literal notranslate\">update_fields</code> iterable will skip the save. A value of <code class=\"docutils literal notranslate\">None</code> will\nperform an update on all fields.</p>\n<p>Specifying <code class=\"docutils literal notranslate\">update_fields</code> will force an update.</p>\n<p>When saving a model fetched through deferred model loading\n(<a class=\"reference internal\" href=\"/es/5.1/ref/models/querysets/#django.db.models.query.QuerySet.only\" title=\"django.db.models.query.QuerySet.only\"><code class=\"xref py py-meth docutils literal notranslate\">only()</code></a> or\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/querysets/#django.db.models.query.QuerySet.defer\" title=\"django.db.models.query.QuerySet.defer\"><code class=\"xref py py-meth docutils literal notranslate\">defer()</code></a>) only the fields loaded\nfrom the DB will get updated. In effect there is an automatic\n<code class=\"docutils literal notranslate\">update_fields</code> in this case. If you assign or change any deferred field\nvalue, the field will be added to the updated fields.</p>\n<aside class=\"admonition-field-pre-save-and-update-fields admonition\" role=\"note\">\n<p class=\"admonition-title\"><code class=\"docutils literal notranslate\">Field.pre_save()</code> and <code class=\"docutils literal notranslate\">update_fields</code></p>\n<p>If <code class=\"docutils literal notranslate\">update_fields</code> is passed in, only the\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.pre_save\" title=\"django.db.models.Field.pre_save\"><code class=\"xref py py-meth docutils literal notranslate\">pre_save()</code></a> methods of the <code class=\"docutils literal notranslate\">update_fields</code>\nare called. For example, this means that date/time fields with\n<code class=\"docutils literal notranslate\">auto_now=True</code> will not be updated unless they are included in the\n<code class=\"docutils literal notranslate\">update_fields</code>.</p>\n</aside>\n</section>\n</section>\n<section id=\"deleting-objects\">\n<h2>Deleting objects<a class=\"heading-anchor\" href=\"#deleting-objects\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.delete\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">delete</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">DEFAULT_DB_ALIAS</span></em>, <em class=\"sig-param\">keep_parents<span class=\"o\">=</span><span class=\"default_value\">False</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.delete\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.adelete\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">adelete</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">DEFAULT_DB_ALIAS</span></em>, <em class=\"sig-param\">keep_parents<span class=\"o\">=</span><span class=\"default_value\">False</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.adelete\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><em>Asynchronous version</em>: <code class=\"docutils literal notranslate\">adelete()</code></p>\n<p>Issues an SQL <code class=\"docutils literal notranslate\">DELETE</code> for the object. This only deletes the object in the\ndatabase; the Python instance will still exist and will still have data in\nits fields, except for the primary key set to <code class=\"docutils literal notranslate\">None</code>. This method returns the\nnumber of objects deleted and a dictionary with the number of deletions per\nobject type.</p>\n<p>For more details, including how to delete objects in bulk, see\n<a class=\"reference internal\" href=\"/es/5.1/topics/db/queries/#topics-db-queries-delete\"><span class=\"std std-ref\">Deleting objects</span></a>.</p>\n<p>If you want customized deletion behavior, you can override the <code class=\"docutils literal notranslate\">delete()</code>\nmethod. See <a class=\"reference internal\" href=\"/es/5.1/topics/db/models/#overriding-model-methods\"><span class=\"std std-ref\">Overriding predefined model methods</span></a> for more details.</p>\n<p>Sometimes with <a class=\"reference internal\" href=\"/es/5.1/topics/db/models/#multi-table-inheritance\"><span class=\"std std-ref\">multi-table inheritance</span></a> you may\nwant to delete only a child model’s data. Specifying <code class=\"docutils literal notranslate\">keep_parents=True</code> will\nkeep the parent model’s data.</p>\n</section>\n<section id=\"pickling-objects\">\n<h2>Pickling objects<a class=\"heading-anchor\" href=\"#pickling-objects\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>When you <a class=\"reference external\" href=\"https://docs.python.org/3/library/pickle.html#module-pickle\" title=\"(en Python versión 3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">pickle</code></a> a model, its current state is pickled. When you unpickle\nit, it’ll contain the model instance at the moment it was pickled, rather than\nthe data that’s currently in the database.</p>\n<aside class=\"admonition-you-can-t-share-pickles-between-versions admonition\" role=\"note\">\n<p class=\"admonition-title\">You can’t share pickles between versions</p>\n<p>Pickles of models are only valid for the version of Django that\nwas used to generate them. If you generate a pickle using Django\nversion N, there is no guarantee that pickle will be readable with\nDjango version N+1. Pickles should not be used as part of a long-term\narchival strategy.</p>\n<p>Since pickle compatibility errors can be difficult to diagnose, such as\nsilently corrupted objects, a <code class=\"docutils literal notranslate\">RuntimeWarning</code> is raised when you try to\nunpickle a model in a Django version that is different than the one in\nwhich it was pickled.</p>\n</aside>\n</section>\n<section id=\"other-model-instance-methods\">\n<span id=\"model-instance-methods\"></span><h2>Other model instance methods<a class=\"heading-anchor\" href=\"#other-model-instance-methods\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>A few object methods have special purposes.</p>\n<section id=\"str\">\n<h3><code class=\"docutils literal notranslate\">__str__()</code><a class=\"heading-anchor\" href=\"#str\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.__str__\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">__str__</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.__str__\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The <code class=\"docutils literal notranslate\">__str__()</code> method is called whenever you call <code class=\"docutils literal notranslate\">str()</code> on an object.\nDjango uses <code class=\"docutils literal notranslate\">str(obj)</code> in a number of places. Most notably, to display an\nobject in the Django admin site and as the value inserted into a template when\nit displays an object. Thus, you should always return a nice, human-readable\nrepresentation of the model from the <code class=\"docutils literal notranslate\">__str__()</code> method.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    first_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n    last_name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">50</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__str__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"sa\">f</span><span class=\"s2\">&quot;</span><span class=\"si\">{</span><span class=\"bp\">self</span><span class=\"o\">.</span>first_name<span class=\"si\">}</span><span class=\"s2\"> </span><span class=\"si\">{</span><span class=\"bp\">self</span><span class=\"o\">.</span>last_name<span class=\"si\">}</span><span class=\"s2\">&quot;</span>\n</code></pre></div>\n</section>\n<section id=\"eq\">\n<h3><code class=\"docutils literal notranslate\">__eq__()</code><a class=\"heading-anchor\" href=\"#eq\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.__eq__\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">__eq__</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.__eq__\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The equality method is defined such that instances with the same primary\nkey value and the same concrete class are considered equal, except that\ninstances with a primary key value of <code class=\"docutils literal notranslate\">None</code> aren’t equal to anything except\nthemselves. For proxy models, concrete class is defined as the model’s first\nnon-proxy parent; for all other models it’s simply the model’s class.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n\n<span class=\"k\">class</span> <span class=\"nc\">MyModel</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"nb\">id</span> <span class=\"o\">=</span> models<span class=\"o\">.</span>AutoField<span class=\"p\">(</span>primary_key<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n\n\n<span class=\"k\">class</span> <span class=\"nc\">MyProxyModel</span><span class=\"p\">(</span>MyModel<span class=\"p\">):</span>\n    <span class=\"k\">class</span> <span class=\"nc\">Meta</span><span class=\"p\">:</span>\n        proxy <span class=\"o\">=</span> <span class=\"kc\">True</span>\n\n\n<span class=\"k\">class</span> <span class=\"nc\">MultitableInherited</span><span class=\"p\">(</span>MyModel<span class=\"p\">):</span>\n    <span class=\"k\">pass</span>\n\n\n<span class=\"c1\"># Primary keys compared</span>\nMyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span> <span class=\"o\">==</span> MyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\nMyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span> <span class=\"o\">!=</span> MyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">2</span><span class=\"p\">)</span>\n<span class=\"c1\"># Primary keys are None</span>\nMyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">)</span> <span class=\"o\">!=</span> MyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">)</span>\n<span class=\"c1\"># Same instance</span>\ninstance <span class=\"o\">=</span> MyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">)</span>\ninstance <span class=\"o\">==</span> instance\n<span class=\"c1\"># Proxy model</span>\nMyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span> <span class=\"o\">==</span> MyProxyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n<span class=\"c1\"># Multi-table inheritance</span>\nMyModel<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span> <span class=\"o\">!=</span> MultitableInherited<span class=\"p\">(</span><span class=\"nb\">id</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n</code></pre></div>\n</section>\n<section id=\"hash\">\n<h3><code class=\"docutils literal notranslate\">__hash__()</code><a class=\"heading-anchor\" href=\"#hash\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.__hash__\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">__hash__</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.__hash__\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>The <code class=\"docutils literal notranslate\">__hash__()</code> method is based on the instance’s primary key value. It\nis effectively <code class=\"docutils literal notranslate\">hash(obj.pk)</code>. If the instance doesn’t have a primary key\nvalue then a <code class=\"docutils literal notranslate\">TypeError</code> will be raised (otherwise the <code class=\"docutils literal notranslate\">__hash__()</code>\nmethod would return different values before and after the instance is\nsaved, but changing the <a class=\"reference external\" href=\"https://docs.python.org/3/reference/datamodel.html#object.__hash__\" title=\"(en Python versión 3.14)\"><code class=\"xref py py-meth docutils literal notranslate\">__hash__()</code></a> value of an instance is\nforbidden in Python.</p>\n</section>\n<section id=\"get-absolute-url\">\n<h3><code class=\"docutils literal notranslate\">get_absolute_url()</code><a class=\"heading-anchor\" href=\"#get-absolute-url\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.get_absolute_url\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">get_absolute_url</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.get_absolute_url\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Define a <code class=\"docutils literal notranslate\">get_absolute_url()</code> method to tell Django how to calculate the\ncanonical URL for an object. To callers, this method should appear to return a\nstring that can be used to refer to the object over HTTP.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">get_absolute_url</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"k\">return</span> <span class=\"s2\">&quot;/people/</span><span class=\"si\">%i</span><span class=\"s2\">/&quot;</span> <span class=\"o\">%</span> <span class=\"bp\">self</span><span class=\"o\">.</span>id\n</code></pre></div>\n<p>While this code is correct and simple, it may not be the most portable way to\nto write this kind of method. The <a class=\"reference internal\" href=\"/es/5.1/ref/urlresolvers/#django.urls.reverse\" title=\"django.urls.reverse\"><code class=\"xref py py-func docutils literal notranslate\">reverse()</code></a> function is\nusually the best approach.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">get_absolute_url</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"kn\">from</span> <span class=\"nn\">django.urls</span> <span class=\"kn\">import</span> reverse\n\n    <span class=\"k\">return</span> reverse<span class=\"p\">(</span><span class=\"s2\">&quot;people-detail&quot;</span><span class=\"p\">,</span> kwargs<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s2\">&quot;pk&quot;</span><span class=\"p\">:</span> <span class=\"bp\">self</span><span class=\"o\">.</span>pk<span class=\"p\">})</span>\n</code></pre></div>\n<p>One place Django uses <code class=\"docutils literal notranslate\">get_absolute_url()</code> is in the admin app. If an object\ndefines this method, the object-editing page will have a «View on site» link\nthat will jump you directly to the object’s public view, as given by\n<code class=\"docutils literal notranslate\">get_absolute_url()</code>.</p>\n<p>Similarly, a couple of other bits of Django, such as the <a class=\"reference internal\" href=\"/es/5.1/ref/contrib/syndication/\"><span class=\"doc\">syndication feed\nframework</span></a>, use <code class=\"docutils literal notranslate\">get_absolute_url()</code> when it is\ndefined. If it makes sense for your model’s instances to each have a unique\nURL, you should define <code class=\"docutils literal notranslate\">get_absolute_url()</code>.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Advertencia</p>\n<p>You should avoid building the URL from unvalidated user input, in order to\nreduce possibilities of link or redirect poisoning:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">get_absolute_url</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"k\">return</span> <span class=\"s2\">&quot;/</span><span class=\"si\">%s</span><span class=\"s2\">/&quot;</span> <span class=\"o\">%</span> <span class=\"bp\">self</span><span class=\"o\">.</span>name\n</code></pre></div>\n<p>If <code class=\"docutils literal notranslate\">self.name</code> is <code class=\"docutils literal notranslate\">'/example.com'</code> this returns <code class=\"docutils literal notranslate\">'//example.com/'</code>\nwhich, in turn, is a valid schema relative URL but not the expected\n<code class=\"docutils literal notranslate\">'/%2Fexample.com/'</code>.</p>\n</aside>\n<p>It’s good practice to use <code class=\"docutils literal notranslate\">get_absolute_url()</code> in templates, instead of\nhard-coding your objects” URLs. For example, this template code is bad:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cm\">&lt;!-- BAD template code. Avoid! --&gt;</span>\n<span class=\"p\">&lt;</span><span class=\"nt\">a</span> <span class=\"na\">href</span><span class=\"o\">=</span><span class=\"s\">&quot;/people/</span><span class=\"cp\">{{</span> <span class=\"nv\">object.id</span> <span class=\"cp\">}}</span><span class=\"s\">/&quot;</span><span class=\"p\">&gt;</span><span class=\"cp\">{{</span> <span class=\"nv\">object.name</span> <span class=\"cp\">}}</span><span class=\"p\">&lt;/</span><span class=\"nt\">a</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n<p>This template code is much better:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">a</span> <span class=\"na\">href</span><span class=\"o\">=</span><span class=\"s\">&quot;</span><span class=\"cp\">{{</span> <span class=\"nv\">object.get_absolute_url</span> <span class=\"cp\">}}</span><span class=\"s\">&quot;</span><span class=\"p\">&gt;</span><span class=\"cp\">{{</span> <span class=\"nv\">object.name</span> <span class=\"cp\">}}</span><span class=\"p\">&lt;/</span><span class=\"nt\">a</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n<p>The logic here is that if you change the URL structure of your objects, even\nfor something small like correcting a spelling error, you don’t want to have to\ntrack down every place that the URL might be created. Specify it once, in\n<code class=\"docutils literal notranslate\">get_absolute_url()</code> and have all your other code call that one place.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Nota</p>\n<p>The string you return from <code class=\"docutils literal notranslate\">get_absolute_url()</code> <strong>must</strong> contain only\nASCII characters (required by the URI specification, <span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc3986.html#section-2\"><strong>RFC 3986 Section 2</strong></a>)\nand be URL-encoded, if necessary.</p>\n<p>Code and templates calling <code class=\"docutils literal notranslate\">get_absolute_url()</code> should be able to use the\nresult directly without any further processing. You may wish to use the\n<code class=\"docutils literal notranslate\">django.utils.encoding.iri_to_uri()</code> function to help with this if you\nare using strings containing characters outside the ASCII range.</p>\n</aside>\n</section>\n</section>\n<section id=\"extra-instance-methods\">\n<h2>Extra instance methods<a class=\"heading-anchor\" href=\"#extra-instance-methods\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>In addition to <a class=\"reference internal\" href=\"#django.db.models.Model.save\" title=\"django.db.models.Model.save\"><code class=\"xref py py-meth docutils literal notranslate\">save()</code></a>, <a class=\"reference internal\" href=\"#django.db.models.Model.delete\" title=\"django.db.models.Model.delete\"><code class=\"xref py py-meth docutils literal notranslate\">delete()</code></a>, a model object\nmight have some of the following methods:</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.get_FOO_display\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">get_FOO_display</span><span class=\"sig-paren\">(</span><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.get_FOO_display\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>For every field that has <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.choices\" title=\"django.db.models.Field.choices\"><code class=\"xref py py-attr docutils literal notranslate\">choices</code></a> set, the\nobject will have a <code class=\"docutils literal notranslate\">get_FOO_display()</code> method, where <code class=\"docutils literal notranslate\">FOO</code> is the name of\nthe field. This method returns the «human-readable» value of the field.</p>\n<p>For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> models\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Person</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    SHIRT_SIZES <span class=\"o\">=</span> <span class=\"p\">{</span>\n        <span class=\"s2\">&quot;S&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;Small&quot;</span><span class=\"p\">,</span>\n        <span class=\"s2\">&quot;M&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;Medium&quot;</span><span class=\"p\">,</span>\n        <span class=\"s2\">&quot;L&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;Large&quot;</span><span class=\"p\">,</span>\n    <span class=\"p\">}</span>\n    name <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">60</span><span class=\"p\">)</span>\n    shirt_size <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">2</span><span class=\"p\">,</span> choices<span class=\"o\">=</span>SHIRT_SIZES<span class=\"p\">)</span>\n</code></pre></div>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Python console code\"><code><span class=\"gp\">&gt;&gt;&gt; </span>p <span class=\"o\">=</span> Person<span class=\"p\">(</span>name<span class=\"o\">=</span><span class=\"s2\">&quot;Fred Flintstone&quot;</span><span class=\"p\">,</span> shirt_size<span class=\"o\">=</span><span class=\"s2\">&quot;L&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>save<span class=\"p\">()</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>shirt_size\n<span class=\"go\">&#39;L&#39;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>p<span class=\"o\">.</span>get_shirt_size_display<span class=\"p\">()</span>\n<span class=\"go\">&#39;Large&#39;</span>\n</code></pre></div>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.get_next_by_FOO\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">get_next_by_FOO</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">**</span>kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.get_next_by_FOO\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model.get_previous_by_FOO\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">get_previous_by_FOO</span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"o\">**</span>kwargs</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.db.models.Model.get_previous_by_FOO\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>For every <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.DateField\" title=\"django.db.models.DateField\"><code class=\"xref py py-class docutils literal notranslate\">DateField</code></a> and\n<a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.DateTimeField\" title=\"django.db.models.DateTimeField\"><code class=\"xref py py-class docutils literal notranslate\">DateTimeField</code></a> that does not have <a class=\"reference internal\" href=\"/es/5.1/ref/models/fields/#django.db.models.Field.null\" title=\"django.db.models.Field.null\"><code class=\"xref py py-attr docutils literal notranslate\">null=True</code></a>, the object will have <code class=\"docutils literal notranslate\">get_next_by_FOO()</code> and\n<code class=\"docutils literal notranslate\">get_previous_by_FOO()</code> methods, where <code class=\"docutils literal notranslate\">FOO</code> is the name of the field. This\nreturns the next and previous object with respect to the date field, raising\na <a class=\"reference internal\" href=\"/es/5.1/ref/models/class/#django.db.models.Model.DoesNotExist\" title=\"django.db.models.Model.DoesNotExist\"><code class=\"xref py py-exc docutils literal notranslate\">DoesNotExist</code></a> exception when appropriate.</p>\n<p>Both of these methods will perform their queries using the default\nmanager for the model. If you need to emulate filtering used by a\ncustom manager, or want to perform one-off custom filtering, both\nmethods also accept optional keyword arguments, which should be in the\nformat described in <a class=\"reference internal\" href=\"/es/5.1/ref/models/querysets/#field-lookups\"><span class=\"std std-ref\">Field lookups</span></a>.</p>\n<p>Note that in the case of identical date values, these methods will use the\nprimary key as a tie-breaker. This guarantees that no records are skipped or\nduplicated. That also means you cannot use those methods on unsaved objects.</p>\n<aside class=\"admonition-overriding-extra-instance-methods admonition\" role=\"note\">\n<p class=\"admonition-title\">Overriding extra instance methods</p>\n<p>In most cases overriding or inheriting <code class=\"docutils literal notranslate\">get_FOO_display()</code>,\n<code class=\"docutils literal notranslate\">get_next_by_FOO()</code>, and <code class=\"docutils literal notranslate\">get_previous_by_FOO()</code> should work as\nexpected. Since they are added by the metaclass however, it is not\npractical to account for all possible inheritance structures. In more\ncomplex cases you should override <code class=\"docutils literal notranslate\">Field.contribute_to_class()</code> to set\nthe methods you need.</p>\n</aside>\n</section>\n<section id=\"other-attributes\">\n<h2>Other attributes<a class=\"heading-anchor\" href=\"#other-attributes\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"state\">\n<h3><code class=\"docutils literal notranslate\">_state</code><a class=\"heading-anchor\" href=\"#state\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.db.models.Model._state\">\n<span class=\"sig-prename descclassname\">Model.</span><span class=\"sig-name descname\">_state</span><a class=\"heading-anchor\" href=\"#django.db.models.Model._state\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>The <code class=\"docutils literal notranslate\">_state</code> attribute refers to a <code class=\"docutils literal notranslate\">ModelState</code> object that tracks\nthe lifecycle of the model instance.</p>\n<p>The <code class=\"docutils literal notranslate\">ModelState</code> object has two attributes: <code class=\"docutils literal notranslate\">adding</code>, a flag which is\n<code class=\"docutils literal notranslate\">True</code> if the model has not been saved to the database yet, and <code class=\"docutils literal notranslate\">db</code>,\na string referring to the database alias the instance was loaded from or\nsaved to.</p>\n<p>Newly instantiated instances have <code class=\"docutils literal notranslate\">adding=True</code> and <code class=\"docutils literal notranslate\">db=None</code>,\nsince they are yet to be saved. Instances fetched from a <code class=\"docutils literal notranslate\">QuerySet</code>\nwill have <code class=\"docutils literal notranslate\">adding=False</code> and <code class=\"docutils literal notranslate\">db</code> set to the alias of the associated\ndatabase.</p>\n</dd></dl>\n\n</section>\n</section>","rootId":"model-instance-reference","toc":[{"title":"Creating objects","anchor":"creating-objects","children":[{"title":"Customizing model loading","anchor":"customizing-model-loading","children":[]}]},{"title":"Refreshing objects from database","anchor":"refreshing-objects-from-database","children":[]},{"title":"Validating objects","anchor":"validating-objects","children":[]},{"title":"Saving objects","anchor":"saving-objects","children":[{"title":"Auto-incrementing primary keys","anchor":"auto-incrementing-primary-keys","children":[{"title":"The pk property","anchor":"the-pk-property","children":[]},{"title":"Explicitly specifying auto-primary-key values","anchor":"explicitly-specifying-auto-primary-key-values","children":[]}]},{"title":"What happens when you save?","anchor":"what-happens-when-you-save","children":[]},{"title":"How Django knows to UPDATE vs. INSERT","anchor":"how-django-knows-to-update-vs-insert","children":[{"title":"Forcing an INSERT or UPDATE","anchor":"forcing-an-insert-or-update","children":[]}]},{"title":"Updating attributes based on existing fields","anchor":"updating-attributes-based-on-existing-fields","children":[]},{"title":"Specifying which fields to save","anchor":"specifying-which-fields-to-save","children":[]}]},{"title":"Deleting objects","anchor":"deleting-objects","children":[]},{"title":"Pickling objects","anchor":"pickling-objects","children":[]},{"title":"Other model instance methods","anchor":"other-model-instance-methods","children":[{"title":"__str__()","anchor":"str","children":[]},{"title":"__eq__()","anchor":"eq","children":[]},{"title":"__hash__()","anchor":"hash","children":[]},{"title":"get_absolute_url()","anchor":"get-absolute-url","children":[]}]},{"title":"Extra instance methods","anchor":"extra-instance-methods","children":[]},{"title":"Other attributes","anchor":"other-attributes","children":[{"title":"_state","anchor":"state","children":[]}]}],"breadcrumbs":[{"docname":"ref/index","title":"API Reference","url":"/es/5.1/ref/"},{"docname":"ref/models/index","title":"Models","url":"/es/5.1/ref/models/"}],"prev":{"docname":"ref/models/options","title":"Model Meta options","url":"/es/5.1/ref/models/options/"},"next":{"docname":"ref/models/querysets","title":"QuerySet API reference","url":"/es/5.1/ref/models/querysets/"},"formats":{"html":"/es/5.1/ref/models/instances/","markdown":"/es/5.1/ref/models/instances.md","json":"/es/5.1/ref/models/instances.json"},"source":"https://github.com/django/django/blob/stable/5.1.x/docs/ref/models/instances.txt","official":"https://docs.djangoproject.com/es/5.1/ref/models/instances/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9"],"inLocales":["en","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}