{"title":"Writing your first Django app, part 2","version":"5.2","locale":"en","docname":"intro/tutorial02","url":"/en/5.2/intro/tutorial02/","canonical":"https://djangodocs.dev/en/5.2/intro/tutorial02/","summary":"This tutorial begins where Tutorial 1 left off. We’ll set up the database, create your first model, and get a quick introduction to Django’s…","html":"<h1>Writing your first Django app, part 2<a class=\"heading-anchor\" href=\"#writing-your-first-django-app-part-2\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>This tutorial begins where <a class=\"reference internal\" href=\"/en/5.2/intro/tutorial01/\"><span class=\"doc\">Tutorial 1</span></a> left off.\nWe’ll set up the database, create your first model, and get a quick\nintroduction to Django’s automatically-generated admin site.</p>\n<aside class=\"admonition-where-to-get-help admonition\" role=\"note\">\n<p class=\"admonition-title\">Where to get help:</p>\n<p>If you’re having trouble going through this tutorial, please head over to\nthe <a class=\"reference internal\" href=\"/en/5.2/faq/help/\"><span class=\"doc\">Getting Help</span></a> section of the FAQ.</p>\n</aside>\n<section id=\"database-setup\">\n<h2>Database setup<a class=\"heading-anchor\" href=\"#database-setup\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Now, open up <code class=\"file docutils literal notranslate\">mysite/settings.py</code>. It’s a normal Python module with\nmodule-level variables representing Django settings.</p>\n<p>By default, the <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-DATABASES\"><code class=\"xref std std-setting docutils literal notranslate\">DATABASES</code></a> configuration uses SQLite. If you’re new\nto databases, or you’re just interested in trying Django, this is the easiest\nchoice. SQLite is included in Python, so you won’t need to install anything\nelse to support your database. When starting your first real project, however,\nyou may want to use a more scalable database like PostgreSQL, to avoid\ndatabase-switching headaches down the road.</p>\n<p>If you wish to use another database, see <a class=\"reference internal\" href=\"/en/5.2/topics/install/#database-installation\"><span class=\"std std-ref\">details to customize and get\nyour database running</span></a>.</p>\n<p>While you’re editing <code class=\"file docutils literal notranslate\">mysite/settings.py</code>, set <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-TIME_ZONE\"><code class=\"xref std std-setting docutils literal notranslate\">TIME_ZONE</code></a> to\nyour time zone.</p>\n<p>Also, note the <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> setting at the top of the file. That\nholds the names of all Django applications that are activated in this Django\ninstance. Apps can be used in multiple projects, and you can package and\ndistribute them for use by others in their projects.</p>\n<p>By default, <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> contains the following apps, all of which\ncome with Django:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/en/5.2/ref/contrib/admin/#module-django.contrib.admin\" title=\"django.contrib.admin: Django's admin site.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.admin</code></a> – The admin site. You’ll use it shortly.</p></li>\n<li><p><a class=\"reference internal\" href=\"/en/5.2/topics/auth/#module-django.contrib.auth\" title=\"django.contrib.auth: Django's authentication framework.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.auth</code></a> – An authentication system.</p></li>\n<li><p><a class=\"reference internal\" href=\"/en/5.2/ref/contrib/contenttypes/#module-django.contrib.contenttypes\" title=\"django.contrib.contenttypes: Provides generic interface to installed models.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.contenttypes</code></a> – A framework for content types.</p></li>\n<li><p><a class=\"reference internal\" href=\"/en/5.2/topics/http/sessions/#module-django.contrib.sessions\" title=\"django.contrib.sessions: Provides session management for Django projects.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.sessions</code></a> – A session framework.</p></li>\n<li><p><a class=\"reference internal\" href=\"/en/5.2/ref/contrib/messages/#module-django.contrib.messages\" title=\"django.contrib.messages: Provides cookie- and session-based temporary message storage.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.messages</code></a> – A messaging framework.</p></li>\n<li><p><a class=\"reference internal\" href=\"/en/5.2/ref/contrib/staticfiles/#module-django.contrib.staticfiles\" title=\"django.contrib.staticfiles: An app for handling static files.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.staticfiles</code></a> – A framework for managing\nstatic files.</p></li>\n</ul>\n<p>These applications are included by default as a convenience for the common case.</p>\n<p>Some of these applications make use of at least one database table, though,\nso we need to create the tables in the database before we can use them. To do\nthat, run the following command:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-0-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py migrate\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-0-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate\n</code></pre></div></div></div>\n<p>The <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a> command looks at the <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> setting\nand creates any necessary database tables according to the database settings\nin your <code class=\"file docutils literal notranslate\">mysite/settings.py</code> file and the database migrations shipped\nwith the app (we’ll cover those later). You’ll see a message for each\nmigration it applies. If you’re interested, run the command-line client for your\ndatabase and type <code class=\"docutils literal notranslate\">\\dt</code> (PostgreSQL), <code class=\"docutils literal notranslate\">SHOW TABLES;</code> (MariaDB, MySQL),\n<code class=\"docutils literal notranslate\">.tables</code> (SQLite), or <code class=\"docutils literal notranslate\">SELECT TABLE_NAME FROM USER_TABLES;</code> (Oracle) to\ndisplay the tables Django created.</p>\n<aside class=\"admonition-for-the-minimalists admonition\" role=\"note\">\n<p class=\"admonition-title\">For the minimalists</p>\n<p>Like we said above, the default applications are included for the common\ncase, but not everybody needs them. If you don’t need any or all of them,\nfeel free to comment-out or delete the appropriate line(s) from\n<a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> before running <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a>. The\n<a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a> command will only run migrations for apps in\n<a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a>.</p>\n</aside>\n</section>\n<section id=\"creating-models\">\n<span id=\"id1\"></span><h2>Creating models<a class=\"heading-anchor\" href=\"#creating-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Now we’ll define your models – essentially, your database layout, with\nadditional metadata.</p>\n<aside class=\"admonition-philosophy admonition\" role=\"note\">\n<p class=\"admonition-title\">Philosophy</p>\n<p>A model is the single, definitive source of information about your data. It\ncontains the essential fields and behaviors of the data you’re storing.\nDjango follows the <a class=\"reference internal\" href=\"/en/5.2/misc/design-philosophies/#dry\"><span class=\"std std-ref\">DRY Principle</span></a>. The goal is to define your\ndata model in one place and automatically derive things from it.</p>\n<p>This includes the migrations - unlike in Ruby On Rails, for example, migrations\nare entirely derived from your models file, and are essentially a\nhistory that Django can roll through to update your database schema to\nmatch your current models.</p>\n</aside>\n<p>In our poll app, we’ll create two models: <code class=\"docutils literal notranslate\">Question</code> and <code class=\"docutils literal notranslate\">Choice</code>. A\n<code class=\"docutils literal notranslate\">Question</code> has a question and a publication date. A <code class=\"docutils literal notranslate\">Choice</code> has two\nfields: the text of the choice and a vote tally. Each <code class=\"docutils literal notranslate\">Choice</code> is associated\nwith a <code class=\"docutils literal notranslate\">Question</code>.</p>\n<p>These concepts are represented by Python classes. Edit the\n<code class=\"file docutils literal notranslate\">polls/models.py</code> file so it looks like this:</p>\n<figure class=\"code-block code-block-captioned\" data-language=\"python\"><figcaption class=\"code-block-caption\"><code class=\"docutils literal notranslate\">polls/models.py</code></figcaption>\n<div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python</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 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\">Question</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    question_text <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">200</span><span class=\"p\">)</span>\n    pub_date <span class=\"o\">=</span> models<span class=\"o\">.</span>DateTimeField<span class=\"p\">(</span><span class=\"s2\">&quot;date published&quot;</span><span class=\"p\">)</span>\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Choice</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    question <span class=\"o\">=</span> models<span class=\"o\">.</span>ForeignKey<span class=\"p\">(</span>Question<span class=\"p\">,</span> on_delete<span class=\"o\">=</span>models<span class=\"o\">.</span>CASCADE<span class=\"p\">)</span>\n    choice_text <span class=\"o\">=</span> models<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">200</span><span class=\"p\">)</span>\n    votes <span class=\"o\">=</span> models<span class=\"o\">.</span>IntegerField<span class=\"p\">(</span>default<span class=\"o\">=</span><span class=\"mi\">0</span><span class=\"p\">)</span>\n</code></pre></figure>\n<p>Here, each model is represented by a class that subclasses\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/instances/#django.db.models.Model\" title=\"django.db.models.Model\"><code class=\"xref py py-class docutils literal notranslate\">django.db.models.Model</code></a>. Each model has a number of class variables,\neach of which represents a database field in the model.</p>\n<p>Each field is represented by an instance of a <a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a>\nclass – e.g., <a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.CharField\" title=\"django.db.models.CharField\"><code class=\"xref py py-class docutils literal notranslate\">CharField</code></a> for character fields and\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.DateTimeField\" title=\"django.db.models.DateTimeField\"><code class=\"xref py py-class docutils literal notranslate\">DateTimeField</code></a> for datetimes. This tells Django what\ntype of data each field holds.</p>\n<p>The name of each <a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> instance (e.g.\n<code class=\"docutils literal notranslate\">question_text</code> or <code class=\"docutils literal notranslate\">pub_date</code>) is the field’s name, in machine-friendly\nformat. You’ll use this value in your Python code, and your database will use\nit as the column name.</p>\n<p>You can use an optional first positional argument to a\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> to designate a human-readable name. That’s used\nin a couple of introspective parts of Django, and it doubles as documentation.\nIf this field isn’t provided, Django will use the machine-readable name. In this\nexample, we’ve only defined a human-readable name for <code class=\"docutils literal notranslate\">Question.pub_date</code>.\nFor all other fields in this model, the field’s machine-readable name will\nsuffice as its human-readable name.</p>\n<p>Some <a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> classes have required arguments.\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.CharField\" title=\"django.db.models.CharField\"><code class=\"xref py py-class docutils literal notranslate\">CharField</code></a>, for example, requires that you give it a\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.CharField.max_length\" title=\"django.db.models.CharField.max_length\"><code class=\"xref py py-attr docutils literal notranslate\">max_length</code></a>. That’s used not only in the\ndatabase schema, but in validation, as we’ll soon see.</p>\n<p>A <a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.Field\" title=\"django.db.models.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> can also have various optional arguments; in\nthis case, we’ve set the <a class=\"reference internal\" href=\"/en/5.2/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> value of\n<code class=\"docutils literal notranslate\">votes</code> to 0.</p>\n<p>Finally, note a relationship is defined, using\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.ForeignKey\" title=\"django.db.models.ForeignKey\"><code class=\"xref py py-class docutils literal notranslate\">ForeignKey</code></a>. That tells Django each <code class=\"docutils literal notranslate\">Choice</code> is\nrelated to a single <code class=\"docutils literal notranslate\">Question</code>. Django supports all the common database\nrelationships: many-to-one, many-to-many, and one-to-one.</p>\n</section>\n<section id=\"activating-models\">\n<h2>Activating models<a class=\"heading-anchor\" href=\"#activating-models\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>That small bit of model code gives Django a lot of information. With it, Django\nis able to:</p>\n<ul class=\"simple\">\n<li><p>Create a database schema (<code class=\"docutils literal notranslate\">CREATE TABLE</code> statements) for this app.</p></li>\n<li><p>Create a Python database-access API for accessing <code class=\"docutils literal notranslate\">Question</code> and <code class=\"docutils literal notranslate\">Choice</code> objects.</p></li>\n</ul>\n<p>But first we need to tell our project that the <code class=\"docutils literal notranslate\">polls</code> app is installed.</p>\n<aside class=\"admonition-philosophy admonition\" role=\"note\">\n<p class=\"admonition-title\">Philosophy</p>\n<p>Django apps are “pluggable”: You can use an app in multiple projects, and\nyou can distribute apps, because they don’t have to be tied to a given\nDjango installation.</p>\n</aside>\n<p>To include the app in our project, we need to add a reference to its\nconfiguration class in the <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> setting. The\n<code class=\"docutils literal notranslate\">PollsConfig</code> class is in the <code class=\"file docutils literal notranslate\">polls/apps.py</code> file, so its dotted path\nis <code class=\"docutils literal notranslate\">'polls.apps.PollsConfig'</code>. Edit the <code class=\"file docutils literal notranslate\">mysite/settings.py</code> file and\nadd that dotted path to the <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a> setting. It’ll look like\nthis:</p>\n<figure class=\"code-block code-block-captioned\" data-language=\"python\"><figcaption class=\"code-block-caption\"><code class=\"docutils literal notranslate\">mysite/settings.py</code></figcaption>\n<div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python</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 code\"><code>INSTALLED_APPS <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"s2\">&quot;polls.apps.PollsConfig&quot;</span><span class=\"p\">,</span>\n    <span class=\"s2\">&quot;django.contrib.admin&quot;</span><span class=\"p\">,</span>\n    <span class=\"s2\">&quot;django.contrib.auth&quot;</span><span class=\"p\">,</span>\n    <span class=\"s2\">&quot;django.contrib.contenttypes&quot;</span><span class=\"p\">,</span>\n    <span class=\"s2\">&quot;django.contrib.sessions&quot;</span><span class=\"p\">,</span>\n    <span class=\"s2\">&quot;django.contrib.messages&quot;</span><span class=\"p\">,</span>\n    <span class=\"s2\">&quot;django.contrib.staticfiles&quot;</span><span class=\"p\">,</span>\n<span class=\"p\">]</span>\n</code></pre></figure>\n<p>Now Django knows to include the <code class=\"docutils literal notranslate\">polls</code> app. Let’s run another command:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-1-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py makemigrations polls\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-1-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py makemigrations polls\n</code></pre></div></div></div>\n<p>You should see something similar to the following:</p>\n<div class=\"code-block\" data-language=\"text\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Text</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=\"Text code\"><code>Migrations for &#39;polls&#39;:\n  polls/migrations/0001_initial.py\n    + Create model Question\n    + Create model Choice\n</code></pre></div>\n<p>By running <code class=\"docutils literal notranslate\">makemigrations</code>, you’re telling Django that you’ve made\nsome changes to your models (in this case, you’ve made new ones) and that\nyou’d like the changes to be stored as a <em>migration</em>.</p>\n<p>Migrations are how Django stores changes to your models (and thus your\ndatabase schema) - they’re files on disk. You can read the migration for your\nnew model if you like; it’s the file <code class=\"docutils literal notranslate\">polls/migrations/0001_initial.py</code>.\nDon’t worry, you’re not expected to read them every time Django makes one, but\nthey’re designed to be human-editable in case you want to manually tweak how\nDjango changes things.</p>\n<p>There’s a command that will run the migrations for you and manage your database\nschema automatically - that’s called <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a>, and we’ll come to it in a\nmoment - but first, let’s see what SQL that migration would run. The\n<a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-sqlmigrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">sqlmigrate</code></a> command takes migration names and returns their SQL:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-2-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py sqlmigrate polls <span class=\"m\">0001</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-2-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py sqlmigrate polls 0001\n</code></pre></div></div></div>\n<p>You should see something similar to the following (we’ve reformatted it for\nreadability):</p>\n<div class=\"code-block\" data-language=\"sql\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">SQL</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=\"SQL code\"><code><span class=\"k\">BEGIN</span><span class=\"p\">;</span>\n<span class=\"c1\">--</span>\n<span class=\"c1\">-- Create model Question</span>\n<span class=\"c1\">--</span>\n<span class=\"k\">CREATE</span> <span class=\"k\">TABLE</span> <span class=\"ss\">&quot;polls_question&quot;</span> <span class=\"p\">(</span>\n    <span class=\"ss\">&quot;id&quot;</span> <span class=\"nb\">bigint</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span> <span class=\"k\">PRIMARY</span> <span class=\"k\">KEY</span> <span class=\"k\">GENERATED</span> <span class=\"k\">BY</span> <span class=\"k\">DEFAULT</span> <span class=\"k\">AS</span> <span class=\"k\">IDENTITY</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;question_text&quot;</span> <span class=\"nb\">varchar</span><span class=\"p\">(</span><span class=\"mi\">200</span><span class=\"p\">)</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;pub_date&quot;</span> <span class=\"k\">timestamp</span> <span class=\"k\">with</span> <span class=\"k\">time</span> <span class=\"k\">zone</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span>\n<span class=\"p\">);</span>\n<span class=\"c1\">--</span>\n<span class=\"c1\">-- Create model Choice</span>\n<span class=\"c1\">--</span>\n<span class=\"k\">CREATE</span> <span class=\"k\">TABLE</span> <span class=\"ss\">&quot;polls_choice&quot;</span> <span class=\"p\">(</span>\n    <span class=\"ss\">&quot;id&quot;</span> <span class=\"nb\">bigint</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span> <span class=\"k\">PRIMARY</span> <span class=\"k\">KEY</span> <span class=\"k\">GENERATED</span> <span class=\"k\">BY</span> <span class=\"k\">DEFAULT</span> <span class=\"k\">AS</span> <span class=\"k\">IDENTITY</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;choice_text&quot;</span> <span class=\"nb\">varchar</span><span class=\"p\">(</span><span class=\"mi\">200</span><span class=\"p\">)</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;votes&quot;</span> <span class=\"nb\">integer</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span><span class=\"p\">,</span>\n    <span class=\"ss\">&quot;question_id&quot;</span> <span class=\"nb\">bigint</span> <span class=\"k\">NOT</span> <span class=\"k\">NULL</span>\n<span class=\"p\">);</span>\n<span class=\"k\">ALTER</span> <span class=\"k\">TABLE</span> <span class=\"ss\">&quot;polls_choice&quot;</span>\n  <span class=\"k\">ADD</span> <span class=\"k\">CONSTRAINT</span> <span class=\"ss\">&quot;polls_choice_question_id_c5b4b260_fk_polls_question_id&quot;</span>\n    <span class=\"k\">FOREIGN</span> <span class=\"k\">KEY</span> <span class=\"p\">(</span><span class=\"ss\">&quot;question_id&quot;</span><span class=\"p\">)</span>\n    <span class=\"k\">REFERENCES</span> <span class=\"ss\">&quot;polls_question&quot;</span> <span class=\"p\">(</span><span class=\"ss\">&quot;id&quot;</span><span class=\"p\">)</span>\n    <span class=\"k\">DEFERRABLE</span> <span class=\"k\">INITIALLY</span> <span class=\"k\">DEFERRED</span><span class=\"p\">;</span>\n<span class=\"k\">CREATE</span> <span class=\"k\">INDEX</span> <span class=\"ss\">&quot;polls_choice_question_id_c5b4b260&quot;</span> <span class=\"k\">ON</span> <span class=\"ss\">&quot;polls_choice&quot;</span> <span class=\"p\">(</span><span class=\"ss\">&quot;question_id&quot;</span><span class=\"p\">);</span>\n\n<span class=\"k\">COMMIT</span><span class=\"p\">;</span>\n</code></pre></div>\n<p>Note the following:</p>\n<ul class=\"simple\">\n<li><p>The exact output will vary depending on the database you are using. The\nexample above is generated for PostgreSQL.</p></li>\n<li><p>Table names are automatically generated by combining the name of the app\n(<code class=\"docutils literal notranslate\">polls</code>) and the lowercase name of the model – <code class=\"docutils literal notranslate\">question</code> and\n<code class=\"docutils literal notranslate\">choice</code>. (You can override this behavior.)</p></li>\n<li><p>Primary keys (IDs) are added automatically. (You can override this, too.)</p></li>\n<li><p>By convention, Django appends <code class=\"docutils literal notranslate\">&quot;_id&quot;</code> to the foreign key field name.\n(Yes, you can override this, as well.)</p></li>\n<li><p>The foreign key relationship is made explicit by a <code class=\"docutils literal notranslate\">FOREIGN KEY</code>\nconstraint. Don’t worry about the <code class=\"docutils literal notranslate\">DEFERRABLE</code> parts; it’s telling\nPostgreSQL to not enforce the foreign key until the end of the transaction.</p></li>\n<li><p>It’s tailored to the database you’re using, so database-specific field types\nsuch as <code class=\"docutils literal notranslate\">auto_increment</code> (MySQL), <code class=\"docutils literal notranslate\">bigint PRIMARY KEY GENERATED BY DEFAULT\nAS IDENTITY</code> (PostgreSQL), or <code class=\"docutils literal notranslate\">integer primary key autoincrement</code> (SQLite)\nare handled for you automatically. Same goes for the quoting of field names\n– e.g., using double quotes or single quotes.</p></li>\n<li><p>The <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-sqlmigrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">sqlmigrate</code></a> command doesn’t actually run the migration on your\ndatabase - instead, it prints it to the screen so that you can see what SQL\nDjango thinks is required. It’s useful for checking what Django is going to\ndo or if you have database administrators who require SQL scripts for\nchanges.</p></li>\n</ul>\n<p>If you’re interested, you can also run\n<a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-check\"><code class=\"xref std std-djadmin docutils literal notranslate\">python manage.py check</code></a>; this checks for any problems in\nyour project without making migrations or touching the database.</p>\n<p>Now, run <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a> again to create those model tables in your database:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-3-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py migrate\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Apply all migrations: admin, auth, contenttypes, polls, sessions</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Applying polls.0001_initial... OK</span>\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-3-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py migrate\n<span class=\"go\">Operations to perform:</span>\n<span class=\"go\">  Apply all migrations: admin, auth, contenttypes, polls, sessions</span>\n<span class=\"go\">Running migrations:</span>\n<span class=\"go\">  Rendering model states... DONE</span>\n<span class=\"go\">  Applying polls.0001_initial... OK</span>\n</code></pre></div></div></div>\n<p>The <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">migrate</code></a> command takes all the migrations that haven’t been\napplied (Django tracks which ones are applied using a special table in your\ndatabase called <code class=\"docutils literal notranslate\">django_migrations</code>) and runs them against your database -\nessentially, synchronizing the changes you made to your models with the schema\nin the database.</p>\n<p>Migrations are very powerful and let you change your models over time, as you\ndevelop your project, without the need to delete your database or tables and\nmake new ones - it specializes in upgrading your database live, without\nlosing data. We’ll cover them in more depth in a later part of the tutorial,\nbut for now, remember the three-step guide to making model changes:</p>\n<ul class=\"simple\">\n<li><p>Change your models (in <code class=\"docutils literal notranslate\">models.py</code>).</p></li>\n<li><p>Run <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-makemigrations\"><code class=\"xref std std-djadmin docutils literal notranslate\">python manage.py makemigrations</code></a> to create\nmigrations for those changes</p></li>\n<li><p>Run <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-migrate\"><code class=\"xref std std-djadmin docutils literal notranslate\">python manage.py migrate</code></a> to apply those changes to\nthe database.</p></li>\n</ul>\n<p>The reason that there are separate commands to make and apply migrations is\nbecause you’ll commit migrations to your version control system and ship them\nwith your app; they not only make your development easier, they’re also\nusable by other developers and in production.</p>\n<p>Read the <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/\"><span class=\"doc\">django-admin documentation</span></a> for full\ninformation on what the <code class=\"docutils literal notranslate\">manage.py</code> utility can do.</p>\n</section>\n<section id=\"playing-with-the-api\">\n<h2>Playing with the API<a class=\"heading-anchor\" href=\"#playing-with-the-api\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Now, let’s hop into the interactive Python shell and play around with the free\nAPI Django gives you. To invoke the Python shell, use this command:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-4-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py shell\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-4-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py shell\n</code></pre></div></div></div>\n<p>We’re using this instead of simply typing “python”, because <code class=\"file docutils literal notranslate\">manage.py</code>\nsets the <span class=\"target\" id=\"index-0\"></span><a class=\"reference internal\" href=\"/en/5.2/topics/settings/#envvar-DJANGO_SETTINGS_MODULE\"><code class=\"xref std std-envvar docutils literal notranslate\">DJANGO_SETTINGS_MODULE</code></a> environment variable, which gives\nDjango the Python import path to your <code class=\"file docutils literal notranslate\">mysite/settings.py</code> file.\nBy default, the <a class=\"reference internal\" href=\"/en/5.2/ref/django-admin/#django-admin-shell\"><code class=\"xref std std-djadmin docutils literal notranslate\">shell</code></a> command automatically imports the models from\nyour <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-INSTALLED_APPS\"><code class=\"xref std std-setting docutils literal notranslate\">INSTALLED_APPS</code></a>.</p>\n<p>Once you’re in the shell, explore the <a class=\"reference internal\" href=\"/en/5.2/topics/db/queries/\"><span class=\"doc\">database API</span></a>:</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=\"go\"># No questions are in the system yet.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet []&gt;</span>\n\n<span class=\"go\"># Create a new Question.</span>\n<span class=\"go\"># Support for time zones is enabled in the default settings file, so</span>\n<span class=\"go\"># Django expects a datetime with tzinfo for pub_date. Use timezone.now()</span>\n<span class=\"go\"># instead of datetime.datetime.now() and it will do the right thing.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">django.utils</span> <span class=\"kn\">import</span> timezone\n<span class=\"gp\">&gt;&gt;&gt; </span>q <span class=\"o\">=</span> Question<span class=\"p\">(</span>question_text<span class=\"o\">=</span><span class=\"s2\">&quot;What&#39;s new?&quot;</span><span class=\"p\">,</span> pub_date<span class=\"o\">=</span>timezone<span class=\"o\">.</span>now<span class=\"p\">())</span>\n\n<span class=\"go\"># Save the object into the database. You have to call save() explicitly.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>save<span class=\"p\">()</span>\n\n<span class=\"go\"># Now it has an ID.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>id\n<span class=\"go\">1</span>\n\n<span class=\"go\"># Access model field values via Python attributes.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>question_text\n<span class=\"go\">&quot;What&#39;s new?&quot;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>pub_date\n<span class=\"go\">datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc)</span>\n\n<span class=\"go\"># Change values by changing the attributes, then calling save().</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>question_text <span class=\"o\">=</span> <span class=\"s2\">&quot;What&#39;s up?&quot;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>save<span class=\"p\">()</span>\n\n<span class=\"go\"># objects.all() displays all the questions in the database.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Question: Question object (1)&gt;]&gt;</span>\n</code></pre></div>\n<p>Wait a minute. <code class=\"docutils literal notranslate\">&lt;Question: Question object (1)&gt;</code> isn’t a helpful\nrepresentation of this object. Let’s fix that by editing the <code class=\"docutils literal notranslate\">Question</code> model\n(in the <code class=\"docutils literal notranslate\">polls/models.py</code> file) and adding a\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/instances/#django.db.models.Model.__str__\" title=\"django.db.models.Model.__str__\"><code class=\"xref py py-meth docutils literal notranslate\">__str__()</code></a> method to both <code class=\"docutils literal notranslate\">Question</code> and\n<code class=\"docutils literal notranslate\">Choice</code>:</p>\n<figure class=\"code-block code-block-captioned\" data-language=\"python\"><figcaption class=\"code-block-caption\"><code class=\"docutils literal notranslate\">polls/models.py</code></figcaption>\n<div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python</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 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\">Question</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\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=\"bp\">self</span><span class=\"o\">.</span>question_text\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Choice</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\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=\"bp\">self</span><span class=\"o\">.</span>choice_text\n</code></pre></figure>\n<p>It’s important to add <a class=\"reference internal\" href=\"/en/5.2/ref/models/instances/#django.db.models.Model.__str__\" title=\"django.db.models.Model.__str__\"><code class=\"xref py py-meth docutils literal notranslate\">__str__()</code></a> methods to your\nmodels, not only for your own convenience when dealing with the interactive\nprompt, but also because objects’ representations are used throughout Django’s\nautomatically-generated admin.</p>\n<p id=\"tutorial02-import-timezone\">Let’s also add a custom method to this model:</p>\n<figure class=\"code-block code-block-captioned\" data-language=\"python\"><figcaption class=\"code-block-caption\"><code class=\"docutils literal notranslate\">polls/models.py</code></figcaption>\n<div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python</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 code\"><code><span class=\"kn\">import</span> <span class=\"nn\">datetime</span>\n\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</span> <span class=\"kn\">import</span> timezone\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Question</span><span class=\"p\">(</span>models<span class=\"o\">.</span>Model<span class=\"p\">):</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">def</span> <span class=\"nf\">was_published_recently</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span>pub_date <span class=\"o\">&gt;=</span> timezone<span class=\"o\">.</span>now<span class=\"p\">()</span> <span class=\"o\">-</span> datetime<span class=\"o\">.</span>timedelta<span class=\"p\">(</span>days<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n</code></pre></figure>\n<p>Note the addition of <code class=\"docutils literal notranslate\">import datetime</code> and <code class=\"docutils literal notranslate\">from django.utils import\ntimezone</code>, to reference Python’s standard <a class=\"reference external\" href=\"https://docs.python.org/3/library/datetime.html#module-datetime\" title=\"(in Python v3.14)\"><code class=\"xref py py-mod docutils literal notranslate\">datetime</code></a> module and Django’s\ntime-zone-related utilities in <a class=\"reference internal\" href=\"/en/5.2/ref/utils/#module-django.utils.timezone\" title=\"django.utils.timezone: Timezone support.\"><code class=\"xref py py-mod docutils literal notranslate\">django.utils.timezone</code></a>, respectively. If\nyou aren’t familiar with time zone handling in Python, you can learn more in\nthe <a class=\"reference internal\" href=\"/en/5.2/topics/i18n/timezones/\"><span class=\"doc\">time zone support docs</span></a>.</p>\n<p>Save these changes and start a new Python interactive shell. (If a\nthree-chevron prompt (&gt;&gt;&gt;) indicates you are still in the shell, you need to\nexit first using <code class=\"docutils literal notranslate\">exit()</code>). Run <code class=\"docutils literal notranslate\">python manage.py shell</code> again to reload\nthe models.</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=\"go\"># Make sure our __str__() addition worked.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Question: What&#39;s up?&gt;]&gt;</span>\n\n<span class=\"go\"># Django provides a rich database lookup API that&#39;s entirely driven by</span>\n<span class=\"go\"># keyword arguments.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<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=\"go\">&lt;QuerySet [&lt;Question: What&#39;s up?&gt;]&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>question_text__startswith<span class=\"o\">=</span><span class=\"s2\">&quot;What&quot;</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;QuerySet [&lt;Question: What&#39;s up?&gt;]&gt;</span>\n\n<span class=\"go\"># Get the question that was published this year.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">django.utils</span> <span class=\"kn\">import</span> timezone\n<span class=\"gp\">&gt;&gt;&gt; </span>current_year <span class=\"o\">=</span> timezone<span class=\"o\">.</span>now<span class=\"p\">()</span><span class=\"o\">.</span>year\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>pub_date__year<span class=\"o\">=</span>current_year<span class=\"p\">)</span>\n<span class=\"go\">&lt;Question: What&#39;s up?&gt;</span>\n\n<span class=\"go\"># Request an ID that doesn&#39;t exist, this will raise an exception.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<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=\"gt\">Traceback (most recent call last):</span>\n    <span class=\"o\">...</span>\n<span class=\"gr\">DoesNotExist</span>: Question matching query does not exist.\n\n<span class=\"x\"># Lookup by a primary key is the most common case, so Django provides a</span>\n<span class=\"x\"># shortcut for primary-key exact lookups.</span>\n<span class=\"x\"># The following is identical to Question.objects.get(id=1).</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>pk<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;Question: What&#39;s up?&gt;</span>\n\n<span class=\"go\"># Make sure our custom method worked.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q <span class=\"o\">=</span> Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>pk<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>was_published_recently<span class=\"p\">()</span>\n<span class=\"go\">True</span>\n\n<span class=\"go\"># Give the Question a couple of Choices. The create call constructs a new</span>\n<span class=\"go\"># Choice object, does the INSERT statement, adds the choice to the set</span>\n<span class=\"go\"># of available choices and returns the new Choice object. Django creates</span>\n<span class=\"go\"># a set (defined as &quot;choice_set&quot;) to hold the &quot;other side&quot; of a ForeignKey</span>\n<span class=\"go\"># relation (e.g. a question&#39;s choice) which can be accessed via the API.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q <span class=\"o\">=</span> Question<span class=\"o\">.</span>objects<span class=\"o\">.</span>get<span class=\"p\">(</span>pk<span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">)</span>\n\n<span class=\"go\"># Display any choices from the related object set -- none so far.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet []&gt;</span>\n\n<span class=\"go\"># Create three choices.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>create<span class=\"p\">(</span>choice_text<span class=\"o\">=</span><span class=\"s2\">&quot;Not much&quot;</span><span class=\"p\">,</span> votes<span class=\"o\">=</span><span class=\"mi\">0</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;Choice: Not much&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>create<span class=\"p\">(</span>choice_text<span class=\"o\">=</span><span class=\"s2\">&quot;The sky&quot;</span><span class=\"p\">,</span> votes<span class=\"o\">=</span><span class=\"mi\">0</span><span class=\"p\">)</span>\n<span class=\"go\">&lt;Choice: The sky&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>create<span class=\"p\">(</span>choice_text<span class=\"o\">=</span><span class=\"s2\">&quot;Just hacking again&quot;</span><span class=\"p\">,</span> votes<span class=\"o\">=</span><span class=\"mi\">0</span><span class=\"p\">)</span>\n\n<span class=\"go\"># Choice objects have API access to their related Question objects.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>question\n<span class=\"go\">&lt;Question: What&#39;s up?&gt;</span>\n\n<span class=\"go\"># And vice versa: Question objects get access to Choice objects.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>all<span class=\"p\">()</span>\n<span class=\"go\">&lt;QuerySet [&lt;Choice: Not much&gt;, &lt;Choice: The sky&gt;, &lt;Choice: Just hacking again&gt;]&gt;</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>count<span class=\"p\">()</span>\n<span class=\"go\">3</span>\n\n<span class=\"go\"># The API automatically follows relationships as far as you need.</span>\n<span class=\"go\"># Use double underscores to separate relationships.</span>\n<span class=\"go\"># This works as many levels deep as you want; there&#39;s no limit.</span>\n<span class=\"go\"># Find all Choices for any question whose pub_date is in this year</span>\n<span class=\"go\"># (reusing the &#39;current_year&#39; variable we created above).</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>Choice<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>question__pub_date__year<span class=\"o\">=</span>current_year<span class=\"p\">)</span>\n<span class=\"go\">&lt;QuerySet [&lt;Choice: Not much&gt;, &lt;Choice: The sky&gt;, &lt;Choice: Just hacking again&gt;]&gt;</span>\n\n<span class=\"go\"># Let&#39;s delete one of the choices. Use delete() for that.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c <span class=\"o\">=</span> q<span class=\"o\">.</span>choice_set<span class=\"o\">.</span>filter<span class=\"p\">(</span>choice_text__startswith<span class=\"o\">=</span><span class=\"s2\">&quot;Just hacking&quot;</span><span class=\"p\">)</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>c<span class=\"o\">.</span>delete<span class=\"p\">()</span>\n</code></pre></div>\n<p>For more information on model relations, see <a class=\"reference internal\" href=\"/en/5.2/ref/models/relations/\"><span class=\"doc\">Accessing related objects</span></a>. For more on how to use double underscores to perform\nfield lookups via the API, see <a class=\"reference internal\" href=\"/en/5.2/topics/db/queries/#field-lookups-intro\"><span class=\"std std-ref\">Field lookups</span></a>. For\nfull details on the database API, see our <a class=\"reference internal\" href=\"/en/5.2/topics/db/queries/\"><span class=\"doc\">Database API reference</span></a>.</p>\n</section>\n<section id=\"introducing-the-django-admin\">\n<h2>Introducing the Django Admin<a class=\"heading-anchor\" href=\"#introducing-the-django-admin\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<aside class=\"admonition-philosophy admonition\" role=\"note\">\n<p class=\"admonition-title\">Philosophy</p>\n<p>Generating admin sites for your staff or clients to add, change, and delete\ncontent is tedious work that doesn’t require much creativity. For that\nreason, Django entirely automates creation of admin interfaces for models.</p>\n<p>Django was written in a newsroom environment, with a very clear separation\nbetween “content publishers” and the “public” site. Site managers use the\nsystem to add news stories, events, sports scores, etc., and that content is\ndisplayed on the public site. Django solves the problem of creating a\nunified interface for site administrators to edit content.</p>\n<p>The admin isn’t intended to be used by site visitors. It’s for site\nmanagers.</p>\n</aside>\n<section id=\"creating-an-admin-user\">\n<h3>Creating an admin user<a class=\"heading-anchor\" href=\"#creating-an-admin-user\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>First we’ll need to create a user who can login to the admin site. Run the\nfollowing command:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-5-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py createsuperuser\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-5-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py createsuperuser\n</code></pre></div></div></div>\n<p>Enter your desired username and press enter.</p>\n<div class=\"code-block\" data-language=\"text\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Text</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=\"Text code\"><code>Username: admin\n</code></pre></div>\n<p>You will then be prompted for your desired email address:</p>\n<div class=\"code-block\" data-language=\"text\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Text</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=\"Text code\"><code>Email address: admin@example.com\n</code></pre></div>\n<p>The final step is to enter your password. You will be asked to enter your\npassword twice, the second time as a confirmation of the first.</p>\n<div class=\"code-block\" data-language=\"text\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Text</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=\"Text code\"><code>Password: **********\nPassword (again): *********\nSuperuser created successfully.\n</code></pre></div>\n</section>\n<section id=\"start-the-development-server\">\n<h3>Start the development server<a class=\"heading-anchor\" href=\"#start-the-development-server\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The Django admin site is activated by default. Let’s start the development\nserver and explore it.</p>\n<p>If the server is not running start it like so:</p>\n<div class=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-6-unix-label\">Linux / macOS</p><div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code><span class=\"gp\">$ </span>python manage.py runserver\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-6-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py manage.py runserver\n</code></pre></div></div></div>\n<p>Now, open a web browser and go to “/admin/” on your local domain – e.g.,\n<a class=\"reference external\" href=\"http://127.0.0.1:8000/admin/\">http://127.0.0.1:8000/admin/</a>. You should see the admin’s login screen:</p>\n<img alt=\"Django admin login screen\" src=\"/en/5.2/_images/admin01.png\" />\n<p>Since <a class=\"reference internal\" href=\"/en/5.2/topics/i18n/translation/\"><span class=\"doc\">translation</span></a> is turned on by default, if\nyou set <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-LANGUAGE_CODE\"><code class=\"xref std std-setting docutils literal notranslate\">LANGUAGE_CODE</code></a>, the login screen will be displayed in the\ngiven language (if Django has appropriate translations).</p>\n</section>\n<section id=\"enter-the-admin-site\">\n<h3>Enter the admin site<a class=\"heading-anchor\" href=\"#enter-the-admin-site\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Now, try logging in with the superuser account you created in the previous step.\nYou should see the Django admin index page:</p>\n<img alt=\"Django admin index page\" src=\"/en/5.2/_images/admin02.png\" />\n<p>You should see a few types of editable content: groups and users. They are\nprovided by <a class=\"reference internal\" href=\"/en/5.2/topics/auth/#module-django.contrib.auth\" title=\"django.contrib.auth: Django's authentication framework.\"><code class=\"xref py py-mod docutils literal notranslate\">django.contrib.auth</code></a>, the authentication framework shipped\nby Django.</p>\n</section>\n<section id=\"make-the-poll-app-modifiable-in-the-admin\">\n<h3>Make the poll app modifiable in the admin<a class=\"heading-anchor\" href=\"#make-the-poll-app-modifiable-in-the-admin\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>But where’s our poll app? It’s not displayed on the admin index page.</p>\n<p>Only one more thing to do: we need to tell the admin that <code class=\"docutils literal notranslate\">Question</code> objects\nhave an admin interface. To do this, open the <code class=\"file docutils literal notranslate\">polls/admin.py</code> file, and\nedit it to look like this:</p>\n<figure class=\"code-block code-block-captioned\" data-language=\"python\"><figcaption class=\"code-block-caption\"><code class=\"docutils literal notranslate\">polls/admin.py</code></figcaption>\n<div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python</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 code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.contrib</span> <span class=\"kn\">import</span> admin\n\n<span class=\"kn\">from</span> <span class=\"nn\">.models</span> <span class=\"kn\">import</span> Question\n\nadmin<span class=\"o\">.</span>site<span class=\"o\">.</span>register<span class=\"p\">(</span>Question<span class=\"p\">)</span>\n</code></pre></figure>\n</section>\n<section id=\"explore-the-free-admin-functionality\">\n<h3>Explore the free admin functionality<a class=\"heading-anchor\" href=\"#explore-the-free-admin-functionality\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Now that we’ve registered <code class=\"docutils literal notranslate\">Question</code>, Django knows that it should be displayed on\nthe admin index page:</p>\n<img alt=\"Django admin index page, now with polls displayed\" src=\"/en/5.2/_images/admin03t.png\" />\n<p>Click “Questions”. Now you’re at the “change list” page for questions. This page\ndisplays all the questions in the database and lets you choose one to change it.\nThere’s the “What’s up?” question we created earlier:</p>\n<img alt=\"Polls change list page\" src=\"/en/5.2/_images/admin04t.png\" />\n<p>Click the “What’s up?” question to edit it:</p>\n<img alt=\"Editing form for question object\" src=\"/en/5.2/_images/admin05t.png\" />\n<p>Things to note here:</p>\n<ul class=\"simple\">\n<li><p>The form is automatically generated from the <code class=\"docutils literal notranslate\">Question</code> model.</p></li>\n<li><p>The different model field types (<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.DateTimeField\" title=\"django.db.models.DateTimeField\"><code class=\"xref py py-class docutils literal notranslate\">DateTimeField</code></a>,\n<a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.CharField\" title=\"django.db.models.CharField\"><code class=\"xref py py-class docutils literal notranslate\">CharField</code></a>) correspond to the appropriate HTML\ninput widget. Each type of field knows how to display itself in the Django\nadmin.</p></li>\n<li><p>Each <a class=\"reference internal\" href=\"/en/5.2/ref/models/fields/#django.db.models.DateTimeField\" title=\"django.db.models.DateTimeField\"><code class=\"xref py py-class docutils literal notranslate\">DateTimeField</code></a> gets free JavaScript\nshortcuts. Dates get a “Today” shortcut and calendar popup, and times get\na “Now” shortcut and a convenient popup that lists commonly entered times.</p></li>\n</ul>\n<p>The bottom part of the page gives you a couple of options:</p>\n<ul class=\"simple\">\n<li><p>Save – Saves changes and returns to the change-list page for this type of\nobject.</p></li>\n<li><p>Save and continue editing – Saves changes and reloads the admin page for\nthis object.</p></li>\n<li><p>Save and add another – Saves changes and loads a new, blank form for this\ntype of object.</p></li>\n<li><p>Delete – Displays a delete confirmation page.</p></li>\n</ul>\n<p>If the value of “Date published” doesn’t match the time when you created the\nquestion in <a class=\"reference internal\" href=\"/en/5.2/intro/tutorial01/\"><span class=\"doc\">Tutorial 1</span></a>, it probably\nmeans you forgot to set the correct value for the <a class=\"reference internal\" href=\"/en/5.2/ref/settings/#std-setting-TIME_ZONE\"><code class=\"xref std std-setting docutils literal notranslate\">TIME_ZONE</code></a> setting.\nChange it, reload the page and check that the correct value appears.</p>\n<p>Change the “Date published” by clicking the “Today” and “Now” shortcuts. Then\nclick “Save and continue editing.” Then click “History” in the upper right.\nYou’ll see a page listing all changes made to this object via the Django admin,\nwith the timestamp and username of the person who made the change:</p>\n<img alt=\"History page for question object\" src=\"/en/5.2/_images/admin06t.png\" />\n<p>When you’re comfortable with the models API and have familiarized yourself with\nthe admin site, read <a class=\"reference internal\" href=\"/en/5.2/intro/tutorial03/\"><span class=\"doc\">part 3 of this tutorial</span></a> to learn\nabout how to add more views to our polls app.</p>\n</section>\n</section>","rootId":"writing-your-first-django-app-part-2","toc":[{"title":"Database setup","anchor":"database-setup","children":[]},{"title":"Creating models","anchor":"creating-models","children":[]},{"title":"Activating models","anchor":"activating-models","children":[]},{"title":"Playing with the API","anchor":"playing-with-the-api","children":[]},{"title":"Introducing the Django Admin","anchor":"introducing-the-django-admin","children":[{"title":"Creating an admin user","anchor":"creating-an-admin-user","children":[]},{"title":"Start the development server","anchor":"start-the-development-server","children":[]},{"title":"Enter the admin site","anchor":"enter-the-admin-site","children":[]},{"title":"Make the poll app modifiable in the admin","anchor":"make-the-poll-app-modifiable-in-the-admin","children":[]},{"title":"Explore the free admin functionality","anchor":"explore-the-free-admin-functionality","children":[]}]}],"breadcrumbs":[{"docname":"intro/index","title":"Getting started","url":"/en/5.2/intro/"}],"prev":{"docname":"intro/tutorial01","title":"Writing your first Django app, part 1","url":"/en/5.2/intro/tutorial01/"},"next":{"docname":"intro/tutorial03","title":"Writing your first Django app, part 3","url":"/en/5.2/intro/tutorial03/"},"formats":{"html":"/en/5.2/intro/tutorial02/","markdown":"/en/5.2/intro/tutorial02.md","json":"/en/5.2/intro/tutorial02.json"},"source":"https://github.com/django/django/blob/stable/5.2.x/docs/intro/tutorial02.txt","official":"https://docs.djangoproject.com/en/5.2/intro/tutorial02/","inVersions":["dev","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","1.8"],"inLocales":["en","sv","zh-hans","ga","fr","ja","id","it","pt-br","ko","es","el","pl"]}