{"id":6249,"date":"2022-12-26T02:57:12","date_gmt":"2022-12-26T02:57:12","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=6249"},"modified":"2023-08-12T08:57:46","modified_gmt":"2023-08-12T08:57:46","slug":"django-orm","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/django-tutorial\/django-orm\/","title":{"rendered":"Django ORM"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about Django ORM and how to use Django ORM API to interact with relational databases.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-django-orm'>Introduction to Django ORM <a href=\"#introduction-to-django-orm\" class=\"anchor\" id=\"introduction-to-django-orm\" title=\"Anchor for Introduction to Django ORM\">#<\/a><\/h2>\n\n\n\n<p>ORM stands for object-relational mapping. ORM is a technique that allows you to manipulate data in a relational database using object-oriented programming.<\/p>\n\n\n\n<p>Django ORM allows you to use the same Python API to interact with various relational databases including PostgreSQL, MySQL, Oracle, and SQLite. <a href=\"https:\/\/docs.djangoproject.com\/en\/4.2\/ref\/databases\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">See a completed list of supported databases here<\/a>.<\/p>\n\n\n\n<p>Django ORM uses the <strong>active record<\/strong> pattern:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A class maps to a single table in the database. The class is often called a model class.<\/li>\n\n\n\n<li>An object of the class maps to a single row in the table.<\/li>\n<\/ul>\n\n\n\n<p>Once you define a model class, you can access predefined methods to create, read, update, and delete data. <\/p>\n\n\n\n<p>Also, Django automatically generates an admin site for managing the data of the models. Let&#8217;s take a look at a simple example to see how Django ORM works.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='setting-up-a-base-project'>Setting up a base project <a href=\"#setting-up-a-base-project\" class=\"anchor\" id=\"setting-up-a-base-project\" title=\"Anchor for Setting up a base project\">#<\/a><\/h2>\n\n\n\n<p>We&#8217;ll set up a base project with a new virtual environment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='creating-a-new-virtual-environment'>Creating a new virtual environment <a href=\"#creating-a-new-virtual-environment\" class=\"anchor\" id=\"creating-a-new-virtual-environment\" title=\"Anchor for Creating a new virtual environment\">#<\/a><\/h3>\n\n\n\n<p>First, <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-virtual-environments\/\">create a new virtual environment<\/a> using the built-in <code>venv<\/code> module:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">python -m venv venv<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, activate the virtual environment:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">venv\\scripts\\activate<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, install the <code>django<\/code>  &amp; <code>django-extensions<\/code> package:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">pip install django django-extensions<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>django-extensions<\/code> package provides you with some custom extensions for the Django framework. We&#8217;ll use <code>django-extensions<\/code> package for outputting the generated SQL by Django ORM.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='creating-a-new-project'>Creating a new project <a href=\"#creating-a-new-project\" class=\"anchor\" id=\"creating-a-new-project\" title=\"Anchor for Creating a new project\">#<\/a><\/h3>\n\n\n\n<p>First, create a new Django project called <code>django_orm<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">django-admin startproject django_orm<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, create an <code>HR<\/code> application inside the <code>django_orm<\/code> project:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">cd django_orm\npython manage.py startapp hr<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, register both <code>hr<\/code> and <code>django_extensions<\/code> in the <code>INSTALLED_APPS<\/code> of the <code>settings.py<\/code> of the project:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-code-table\"><span class='shcb-loc'><span>INSTALLED_APPS = &#91;\n<\/span><\/span><span class='shcb-loc'><span>    <span class=\"hljs-comment\"># ...<\/span>\n<\/span><\/span><mark class='shcb-loc'><span>    <span class=\"hljs-string\">'django_extensions'<\/span>,\n<\/span><\/mark><mark class='shcb-loc'><span>    <span class=\"hljs-string\">'hr'<\/span>,\n<\/span><\/mark><span class='shcb-loc'><span>]\n<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id='setting-up-the-postgresql-database-server'>Setting up the PostgreSQL database server <a href=\"#setting-up-the-postgresql-database-server\" class=\"anchor\" id=\"setting-up-the-postgresql-database-server\" title=\"Anchor for Setting up the PostgreSQL database server\">#<\/a><\/h3>\n\n\n\n<p>First, <a href=\"https:\/\/www.postgresqltutorial.com\/postgresql-getting-started\/install-postgresql\/\" target=\"_blank\" rel=\"noreferrer noopener\">install a PostgreSQL database server on your local computer<\/a>.<\/p>\n\n\n\n<p>Second, log in to the PostgreSQL database server. It&#8217;ll prompt you for the password of the <code>postgres<\/code> user. Note that you use the same password you entered for the <code>postgres<\/code> user during the installation.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">psql -U postgres\nPassword <span class=\"hljs-keyword\">for<\/span> user postgres:<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, create a new database with the name <code>hr<\/code> and type <code>exit<\/code> to quit the <code>psql<\/code> program:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">postgres=<span class=\"hljs-comment\"># create database hr;<\/span>\nCREATE DATABASE\npostgres=<span class=\"hljs-comment\"># exit<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\" id='connecting-to-the-postgresql-from-django'>Connecting to the PostgreSQL from Django <a href=\"#connecting-to-the-postgresql-from-django\" class=\"anchor\" id=\"connecting-to-the-postgresql-from-django\" title=\"Anchor for Connecting to the PostgreSQL from Django\">#<\/a><\/h3>\n\n\n\n<p>First, configure the database connection in the <code>settings.py<\/code> of the <code>django_orm<\/code> project:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">DATABASES = {\n    <span class=\"hljs-string\">'default'<\/span>: {\n        <span class=\"hljs-string\">'ENGINE'<\/span>: <span class=\"hljs-string\">'django.db.backends.postgresql'<\/span>,\n        <span class=\"hljs-string\">'NAME'<\/span>: <span class=\"hljs-string\">'hr'<\/span>,\n        <span class=\"hljs-string\">'USER'<\/span>: <span class=\"hljs-string\">'postgres'<\/span>,\n        <span class=\"hljs-string\">'PASSWORD'<\/span>: <span class=\"hljs-string\">'POSTGRES_PASSWORD'<\/span>,\n        <span class=\"hljs-string\">'HOST'<\/span>: <span class=\"hljs-string\">'localhost'<\/span>,\n        <span class=\"hljs-string\">'PORT'<\/span>: <span class=\"hljs-string\">''<\/span>,\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"note\">Note that you change the <code>POSTGRES_PASSWORD<\/code> to your password.<\/p>\n\n\n\n<p>Second, install the <code>psycopg2<\/code> package to allow Django to connect to the <code>PostgreSQL<\/code> database server:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">pip install psycopg2<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, run the Django development server:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">python manage.py runserver<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>You&#8217;ll see the Django default homepage:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"641\" height=\"428\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/Django-ORM-homepage.png\" alt=\"Django ORM homepage\" class=\"wp-image-6251\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/Django-ORM-homepage.png 641w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/Django-ORM-homepage-300x200.png 300w\" sizes=\"auto, (max-width: 641px) 100vw, 641px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id='defining-a-model'>Defining a model <a href=\"#defining-a-model\" class=\"anchor\" id=\"defining-a-model\" title=\"Anchor for Defining a model\">#<\/a><\/h2>\n\n\n\n<p>First, define an <code>Employee<\/code> class in the <code>hr<\/code> application that has two fields <code>first_name<\/code> and <code>last_name<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> django.db <span class=\"hljs-keyword\">import<\/span> models\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Employee<\/span><span class=\"hljs-params\">(models.Model)<\/span>:<\/span>\n    first_name = models.CharField(max_length=<span class=\"hljs-number\">100<\/span>)\n    last_name = models.CharField(max_length=<span class=\"hljs-number\">100<\/span>)\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__str__<\/span><span class=\"hljs-params\">(self)<\/span>:<\/span>\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">f'<span class=\"hljs-subst\">{self.first_name}<\/span> <span class=\"hljs-subst\">{self.last_name}<\/span>'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, make migrations using the <code>makemigrations<\/code> command:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">python manage.py makemigrations<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Migrations <span class=\"hljs-keyword\">for<\/span> <span class=\"hljs-string\">'hr'<\/span>:\n  hr\\migrations\\<span class=\"hljs-number\">0001<\/span>_initial.py\n    - Create model Employee<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, propagate the changes to the database using the <code>migrate<\/code> command:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">python manage.py migrate<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Django creates a lot of tables including the ones for the built-in models such as <code>User<\/code> and <code>Group<\/code>. In this tutorial, we&#8217;ll focus on the <code>Employee<\/code> class.<\/p>\n\n\n\n<p>Based on the <code>Employee<\/code> model class, Django ORM creates a table <code>hr_employee<\/code> in the database:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"355\" height=\"209\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/Django-ORM-example.png\" alt=\"Django ORM example\" class=\"wp-image-6250\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/Django-ORM-example.png 355w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/Django-ORM-example-300x177.png 300w\" sizes=\"auto, (max-width: 355px) 100vw, 355px\" \/><\/figure>\n\n\n\n<p>Django combines the app name and class name to generate the table name:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">app_modelclass<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the app name is <code>hr<\/code> and the class name is <code>Employee<\/code>. Therefore, Django creates the table with the name <code>hr_employee<\/code>. Note that Django converts the class name to lowercase before appending it to the app name.<\/p>\n\n\n\n<p>The <code>Employee<\/code> model class has two fields <code>first_name<\/code> and <code>last_name<\/code>. Since the Employee class inherits from <code>models.Model<\/code> class, Django automatically adds the id field as an auto-increment field called <code>id<\/code>. Therefore, the <code>hr_employee<\/code> table has three columns <code>id<\/code>, <code>first_name<\/code>, and <code>last_name<\/code>.<\/p>\n\n\n\n<p>To interact with the <code>hr_employee<\/code> table, you can run the <code>shell_plus<\/code> command that comes from the <code>django-extensions<\/code> package.<\/p>\n\n\n\n<p class=\"note\">Note that Django provides you with a built-in <code>shell<\/code> command. However, the <code>shell_plus<\/code> command is more convenient to work with. For example, it automatically loads the models defined in the project and displays the generated SQL.<\/p>\n\n\n\n<p>Run the <code>shell_plus<\/code> command with the <code>--print-sql<\/code> option:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">python manage.py shell_plus --<span class=\"hljs-keyword\">print<\/span>-sql<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='inserting-data'>Inserting data <a href=\"#inserting-data\" class=\"anchor\" id=\"inserting-data\" title=\"Anchor for Inserting data\">#<\/a><\/h2>\n\n\n\n<p>First, create a new <code>Employee<\/code> object and call the <code>save()<\/code> method to insert a new row into the table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e = Employee(first_name=<span class=\"hljs-string\">'John'<\/span>,last_name=<span class=\"hljs-string\">'Doe'<\/span>)\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e.save()\nINSERT INTO <span class=\"hljs-string\">\"hr_employee\"<\/span> (<span class=\"hljs-string\">\"first_name\"<\/span>, <span class=\"hljs-string\">\"last_name\"<\/span>)\nVALUES (<span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-string\">'Doe'<\/span>) RETURNING <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span>\nExecution time: <span class=\"hljs-number\">0.003234<\/span>s &#91;Database: default]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, you don&#8217;t need to set the value for the id column. The database automatically generates its value and Django will set it once you insert a new row into the table.<\/p>\n\n\n\n<p>As shown in the output, Django uses the <code>INSERT<\/code> statement to insert a new row with two columns <code>first_name<\/code> and <code>last_name<\/code> into <code>hr_employee<\/code> table.<\/p>\n\n\n\n<p>Second, insert the second employee with the first name <code>Jane<\/code> and last name <code>Doe<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e = Employee(first_name=<span class=\"hljs-string\">'Jane'<\/span>,last_name=<span class=\"hljs-string\">'Doe'<\/span>)\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e.save()\nINSERT INTO <span class=\"hljs-string\">\"hr_employee\"<\/span> (<span class=\"hljs-string\">\"first_name\"<\/span>, <span class=\"hljs-string\">\"last_name\"<\/span>)\nVALUES (<span class=\"hljs-string\">'Jane'<\/span>, <span class=\"hljs-string\">'Doe'<\/span>) RETURNING <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span>\nExecution time: <span class=\"hljs-number\">0.002195<\/span>s &#91;Database: default]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, the <code>hr_employee<\/code> table has two rows with id 1 and 2.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='selecting-data'>Selecting data <a href=\"#selecting-data\" class=\"anchor\" id=\"selecting-data\" title=\"Anchor for Selecting data\">#<\/a><\/h2>\n\n\n\n<p>To select all rows from the <code>hr_employees<\/code> table, you use the <code>all()<\/code> method like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>Employee.objects.all()\nSELECT <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"first_name\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"last_name\"<\/span>\n  FROM <span class=\"hljs-string\">\"hr_employee\"<\/span>\n LIMIT <span class=\"hljs-number\">21<\/span>\nExecution time: <span class=\"hljs-number\">0.001856<\/span>s &#91;Database: default]\n&lt;QuerySet &#91;&lt;Employee: John Doe&gt;, &lt;Employee: Jane Doe&gt;]&gt;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, Django uses the <code>SELECT<\/code> statement to select rows from the <code>hr_employee<\/code> table. <\/li>\n\n\n\n<li>Second, Django converts rows into <code>Employee<\/code> objects and returns a <code>QuerySet<\/code> which contains the <code>Employee<\/code> objects.<\/li>\n<\/ul>\n\n\n\n<p class=\"note\">Notice that <code><a href=\"https:\/\/www.postgresqltutorial.com\/postgresql-tutorial\/postgresql-limit\/\" target=\"_blank\" rel=\"noreferrer noopener\">LIMIT<\/a><\/code> is added by Django to return 21 records for displaying on the shell.<\/p>\n\n\n\n<p>To select a single row by id, you can use the <code>get()<\/code> method. For example, the following returns the employee with id 1:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e = Employee.objects.get(id=<span class=\"hljs-number\">1<\/span>)\nSELECT <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"first_name\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"last_name\"<\/span>\n  FROM <span class=\"hljs-string\">\"hr_employee\"<\/span>\n WHERE <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span> = <span class=\"hljs-number\">1<\/span>\n LIMIT <span class=\"hljs-number\">21<\/span>\nExecution time: <span class=\"hljs-number\">0.001003<\/span>s &#91;Database: default]\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e\n&lt;Employee: John Doe&gt;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Unlike the <code>all()<\/code> method, the <code>get()<\/code> method returns an <code>Employee<\/code> object instead of a <code>QuerySet<\/code>.<\/p>\n\n\n\n<p>To find employees by their first name, you can use the <code>filter()<\/code> method of the <code>QuerySet<\/code> object. For example, the following finds employees with the first name <code>Jane<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-22\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>Employee.objects.filter(first_name=<span class=\"hljs-string\">'Jane'<\/span>)\nSELECT <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"first_name\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"last_name\"<\/span>\n  FROM <span class=\"hljs-string\">\"hr_employee\"<\/span>\n WHERE <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"first_name\"<\/span> = <span class=\"hljs-string\">'Jane'<\/span>\n LIMIT <span class=\"hljs-number\">21<\/span>\nExecution time: <span class=\"hljs-number\">0.000000<\/span>s &#91;Database: default]\n&lt;QuerySet &#91;&lt;Employee: Jane Doe&gt;]&gt;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='updating-data'>Updating data <a href=\"#updating-data\" class=\"anchor\" id=\"updating-data\" title=\"Anchor for Updating data\">#<\/a><\/h2>\n\n\n\n<p>First, select the employee with id 2:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-23\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e = Employee.objects.get(id=<span class=\"hljs-number\">2<\/span>)\nSELECT <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"first_name\"<\/span>,\n       <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"last_name\"<\/span>\n  FROM <span class=\"hljs-string\">\"hr_employee\"<\/span>\n WHERE <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span> = <span class=\"hljs-number\">2<\/span>\n LIMIT <span class=\"hljs-number\">21<\/span>\nExecution time: <span class=\"hljs-number\">0.001022<\/span>s &#91;Database: default]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-23\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, update the last name of the selected employee to <code>Smith<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-24\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e.last_name = <span class=\"hljs-string\">'Smith'<\/span>\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e.save()\nUPDATE <span class=\"hljs-string\">\"hr_employee\"<\/span>\n   SET <span class=\"hljs-string\">\"first_name\"<\/span> = <span class=\"hljs-string\">'Jane'<\/span>,\n       <span class=\"hljs-string\">\"last_name\"<\/span> = <span class=\"hljs-string\">'Smith'<\/span>\n WHERE <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span> = <span class=\"hljs-number\">2<\/span>\nExecution time: <span class=\"hljs-number\">0.004019<\/span>s &#91;Database: default]\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e\n&lt;Employee: Jane Smith&gt;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-24\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='deleting-data'>Deleting data <a href=\"#deleting-data\" class=\"anchor\" id=\"deleting-data\" title=\"Anchor for Deleting data\">#<\/a><\/h2>\n\n\n\n<p>To delete an instance of a model, you use the <code>delete()<\/code> method. The following example deletes the employee with id 2:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-25\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>e.delete()\nDELETE\n  FROM <span class=\"hljs-string\">\"hr_employee\"<\/span>\n WHERE <span class=\"hljs-string\">\"hr_employee\"<\/span>.<span class=\"hljs-string\">\"id\"<\/span> IN (<span class=\"hljs-number\">2<\/span>)\nExecution time: <span class=\"hljs-number\">0.002001<\/span>s &#91;Database: default]\n(<span class=\"hljs-number\">1<\/span>, {<span class=\"hljs-string\">'hr.Employee'<\/span>: <span class=\"hljs-number\">1<\/span>})<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-25\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To delete all instances of a model, you use the <code>all()<\/code> method to select all employees and call the <code>delete()<\/code> method to delete all the selected employees:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-26\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>Employee.objects.all().delete()\nDELETE\n  FROM <span class=\"hljs-string\">\"hr_employee\"<\/span>\nExecution time: <span class=\"hljs-number\">0.001076<\/span>s &#91;Database: default]\n(<span class=\"hljs-number\">1<\/span>, {<span class=\"hljs-string\">'hr.Employee'<\/span>: <span class=\"hljs-number\">1<\/span>})<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-26\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Django uses the <code><a href=\"https:\/\/www.postgresqltutorial.com\/postgresql-tutorial\/postgresql-delete\/\" target=\"_blank\" rel=\"noreferrer noopener\">DELETE<\/a><\/code> statement without a <code><a href=\"https:\/\/www.postgresqltutorial.com\/postgresql-tutorial\/postgresql-where\/\" target=\"_blank\" rel=\"noreferrer noopener\">WHERE<\/a><\/code> clause to delete all rows from the <code>hr_employee<\/code> table.<\/p>\n\n\n\n<p class=\"note\">Download the <a href=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/12\/django_orm_1.zip\" target=\"_blank\" rel=\"noreferrer noopener\">Django ORM<\/a> here.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Django ORM allows you to interact with relational databases using Python API.<\/li>\n\n\n\n<li>Django ORM uses the active record pattern, in which a class maps to a table and an object maps to a row. <\/li>\n\n\n\n<li>Use <code>all()<\/code> method to get all rows from a table.<\/li>\n\n\n\n<li>Use <code>get()<\/code> method to select a row by id.<\/li>\n\n\n\n<li>Use <code>filter()<\/code> method to filter rows by one or more fields.<\/li>\n\n\n\n<li>Use <code>save()<\/code> method to create a new row or update an existing row.<\/li>\n\n\n\n<li>Use <code>delete()<\/code> method to delete one or more rows from a table.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"6249\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/django-tutorial\/django-orm\/\"\n\t\t\t\tdata-post-title=\"Django ORM\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"6249\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/django-tutorial\/django-orm\/\"\n\t\t\t\tdata-post-title=\"Django ORM\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about Django ORM and how to use Django ORM API to interact with relational databases.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":5531,"menu_order":22,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-6249","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6249","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=6249"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/6249\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/5531"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=6249"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}