{"id":120137,"date":"2024-12-16T14:40:26","date_gmt":"2024-12-16T14:40:26","guid":{"rendered":"\/tutorials\/?p=120137"},"modified":"2025-12-18T22:45:12","modified_gmt":"2025-12-18T22:45:12","slug":"django-models-and-databases","status":"publish","type":"post","link":"\/my\/tutorials\/django-models-and-databases","title":{"rendered":"How to work with Django models and databases"},"content":{"rendered":"<p>Django models are the heart of data management in any Django application. They define the structure of your database and serve as the foundation for creating dynamic, data-driven applications. <\/p><p>With Django&rsquo;s powerful object-relational mapping (ORM) system, working with models becomes seamless, enabling you to define, query, and manipulate data effortlessly. <\/p><p>Let&rsquo;s explore how Django models and databases work together to bring your application to life.<\/p><p>\n\n\n\n\n\n\n<\/p><h2 class=\"wp-block-heading\" id=\"h-what-are-django-models\">What are Django models?<\/h2><p>In Django, <strong>models<\/strong> define the structure of your database tables. They are Python classes that map directly to database tables, so you can interact with your data in a convenient, high-level way.<\/p><p>Each model class represents a table, and each model attribute represents a field in that table.<\/p><p>Django&rsquo;s ORM system eliminates the need to write raw SQL queries, simplifying tasks like creating, updating, and managing database records.<\/p><h2 class=\"wp-block-heading\" id=\"h-how-to-create-a-django-model\">How to create a Django model?<\/h2><p>To create a model, you define a Python class inside the <strong>models.py<\/strong> file of one of your apps. Each attribute in the class represents a database field, and Django will automatically handle the underlying database structure when you run migrations.<\/p><p>Here&rsquo;s an example of a simple model in Django:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># In your app's models.py file\n\nfrom django.db import models\n\nclass Book(models.Model):\n\n&nbsp;&nbsp;&nbsp;&nbsp;title = models.CharField(max_length=200)\n\n&nbsp;&nbsp;&nbsp;&nbsp;author = models.CharField(max_length=100)\n\n&nbsp;&nbsp;&nbsp;&nbsp;published_date = models.DateField()\n\n&nbsp;&nbsp;&nbsp;&nbsp;isbn = models.CharField(max_length=13, unique=True)\n\n&nbsp;&nbsp;&nbsp;&nbsp;def __str__(self):\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return self.title<\/pre><ul class=\"wp-block-list\">\n<li><strong>title<\/strong> and <strong>author<\/strong> &ndash; these are character fields (<strong>CharField<\/strong>) with a maximum length.<\/li>\n\n\n\n<li><strong>published_date<\/strong> &ndash; this is a date field (<strong>DateField<\/strong>).<\/li>\n\n\n\n<li><strong>isbn<\/strong> &ndash; a character field (<strong>CharField<\/strong>) with a unique constraint (<strong>unique=True<\/strong>).<\/li>\n<\/ul><p>The <strong>__str__()<\/strong> method ensures that when you query for a book, it will return the book&rsquo;s title as a string representation.<\/p><h3 class=\"wp-block-heading\" id=\"h-model-fields\">Model fields<\/h3><p>In Django, model fields define the data type you want to store in your database. Each field type specifies how the data will be stored and validated.<\/p><p>Below are some of the most common field types:<\/p><ul class=\"wp-block-list\">\n<li><strong>CharField<\/strong> &ndash; for short text (e.g. names).<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">name = models.CharField(max_length=100)<\/pre><ul class=\"wp-block-list\">\n<li><strong>TextField<\/strong> &ndash; for long text (e.g. descriptions).<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">description = models.TextField()<\/pre><ul class=\"wp-block-list\">\n<li><strong>IntegerField<\/strong> &ndash; for whole numbers.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">age = models.IntegerField()<\/pre><ul class=\"wp-block-list\">\n<li><strong>FloatField<\/strong> &ndash; for decimal numbers.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">price = models.FloatField()<\/pre><ul class=\"wp-block-list\">\n<li><strong>BooleanField<\/strong> &ndash; for <strong>True<\/strong> or <strong>False<\/strong> values.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">is_active = models.BooleanField(default=True)<\/pre><ul class=\"wp-block-list\">\n<li><strong>DateField<\/strong> &ndash; for storing dates.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">birth_date = models.DateField()<\/pre><ul class=\"wp-block-list\">\n<li><strong>DateTimeField<\/strong> &ndash; for storing both date and time.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">created_at = models.DateTimeField(auto_now_add=True)<\/pre><ul class=\"wp-block-list\">\n<li><strong>ForeignKey<\/strong> &ndash; for creating a many-to-one relationship with another model.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">user = models.ForeignKey(User, on_delete=models.CASCADE)<\/pre><ul class=\"wp-block-list\">\n<li><strong>ManyToManyField<\/strong> &ndash; for creating a many-to-many relationship between models.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">tags = models.ManyToManyField(Tag)<\/pre><h3 class=\"wp-block-heading\" id=\"h-model-relationships\">Model relationships<\/h3><p>Model relationships define how models are connected to each other. Django provides three main types of relationships:<\/p><ul class=\"wp-block-list\">\n<li><strong>ForeignKey<\/strong> &ndash; defines a many-to-one relationship. One object in this model is linked to one object in another model (e.g., a post belongs to a user).<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">user = models.ForeignKey(User, on_delete=models.CASCADE)<\/pre><ul class=\"wp-block-list\">\n<li><strong>OneToOneField<\/strong> &ndash; defines a one-to-one relationship. Each object in one model is linked to exactly one object in another model (e.g., a user has one profile).<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">profile = models.OneToOneField(Profile, on_delete=models.CASCADE)<\/pre><ul class=\"wp-block-list\">\n<li><strong>ManyToManyField<\/strong> &ndash; defines a many-to-many relationship. Many objects of one model can be linked to many objects of another model (e.g., a post can have multiple tags, and each tag can belong to multiple posts).<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">tags = models.ManyToManyField(Tag)<\/pre><p>These relationships let you create connections between models and establish links between data in your database.<\/p><h2 class=\"wp-block-heading\" id=\"h-adding-the-model-to-the-database\">Adding the model to the database<\/h2><p>Once you&rsquo;ve created your model, Django needs to translate it into a database table. This is done through <strong>migrations<\/strong>, which are files that Django uses to apply changes to the database schema and keep track of changes in your models.<\/p><h3 class=\"wp-block-heading\" id=\"h-creating-migrations\">Creating migrations<\/h3><p>To create the migration file for your new model, run the following command:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python manage.py makemigrations<\/pre><p>Django will analyze the changes in your <strong>models.py<\/strong> file and generate a migration file that describes those changes in a format that Django can apply to the database.<\/p><p>You&rsquo;ll see output similar to this:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Migrations for 'myapp':\n\n&nbsp;&nbsp;myapp\/migrations\/0001_initial.py\n\n&nbsp;&nbsp;&nbsp;&nbsp;- Create model Book<\/pre><h3 class=\"wp-block-heading\" id=\"h-applying-migrations\">Applying migrations<\/h3><p>After generating the migration, apply it to the database using the <strong>migrate<\/strong> command:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python manage.py migrate<\/pre><p>This command will create the necessary tables in your database. Now, the <strong>Book<\/strong> model is represented by a corresponding <strong>Book<\/strong> table in your database, and you can start adding, querying, and managing data.<\/p><h2 class=\"wp-block-heading\" id=\"h-setting-up-the-default-database\">Setting up the default database<\/h2><p>Django supports multiple databases, so you can choose the best one for your project. By default, Django uses <strong>SQLite<\/strong>, which is lightweight, easy to set up, and ideal for development and small projects.<\/p><p>For production environments, we recommend more robust databases like <strong>PostgreSQL<\/strong>, <strong>MySQL<\/strong>, or <strong>MariaDB<\/strong> due to their scalability and performance.<\/p><p>In this tutorial, let&rsquo;s start by setting up the default SQLite database.<\/p><h3 class=\"wp-block-heading\" id=\"h-configuring-the-database-in-settings-py\">Configuring the database in settings.py<\/h3><p>By default, Django is configured to use SQLite, which comes pre-installed with Python, so no additional setup is needed. Here&rsquo;s how to make sure your project is set up to use SQLite:<\/p><ol class=\"wp-block-list\">\n<li>Navigate to your project&rsquo;s <strong>settings.py<\/strong> file, which is located in the project folder (<strong>myproject\/myproject\/settings.py<\/strong>).<\/li>\n\n\n\n<li>Go to the <strong>DATABASES<\/strong> section in <strong>settings.py<\/strong>, where Django has already configured SQLite as the default database. It should look like this:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DATABASES = {\n\n&nbsp;&nbsp;&nbsp;&nbsp;'default': {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'ENGINE': 'django.db.backends.sqlite3',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'NAME': BASE_DIR \/ 'db.sqlite3',\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>ENGINE<\/strong> &ndash; specifies the database backend (in this case, SQLite).<\/li>\n\n\n\n<li><strong>NAME<\/strong> &ndash; the path to the SQLite database file (<strong>db.sqlite3<\/strong>). Django will automatically create this file when you run the initial migration.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-applying-migrations-for-default-tables\">Applying migrations for default tables<\/h3><p>After confirming your database settings, you need to apply the initial migrations to set up the default tables (like <strong>users<\/strong> and <strong>sessions<\/strong>). Run the following command:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python manage.py migrate<\/pre><p>This command will create the <strong>db.sqlite3<\/strong> file in your project directory&rsquo;s root and set up all the necessary tables for your application to run.<\/p><p>Once the migrations are complete, check that <strong>db.sqlite3<\/strong> was created in your project folder. This file stores your database locally and will grow as you add more data.<\/p><h2 class=\"wp-block-heading\" id=\"h-using-other-databases-for-django-production\">Using other databases for Django production<\/h2><p>Once you&rsquo;ve set up the default SQLite database for development, you may need to integrate a more robust database management system (DBMS) as your project grows.<\/p><p>Django supports multiple DBMSs, including <strong>PostgreSQL<\/strong>, <strong>MySQL<\/strong>, <strong>MariaDB<\/strong>, and <strong>Oracle<\/strong>. Each has its own strengths and requires a specific configuration for integration with Django.<\/p><h3 class=\"wp-block-heading\" id=\"h-overview-of-other-supported-databases-in-django\">Overview of other Supported databases in Django<\/h3><p>Let&rsquo;s take a look at each of the options and how they differ from SQLite:<\/p><p><strong>PostgreSQL<\/strong><\/p><p>A powerful, open-source database with advanced features, such as support for complex queries, data types like JSON, and full-text search. It&rsquo;s highly recommended for production Django applications due to its scalability, robustness, and feature set.<\/p><p>PostgreSQL is known for strictly adhering to SQL standards and is reliable for complex and large-scale applications.<\/p><ul class=\"wp-block-list\">\n<li><strong>Setup<\/strong> &ndash; PostgreSQL requires installing the <strong>psycopg2<\/strong> package, which acts as the adapter between Django and PostgreSQL.<\/li>\n\n\n\n<li><strong>Configuration<\/strong> &ndash; in addition to the default <strong>ENGINE<\/strong> and <strong>NAME<\/strong> parameters for SQLite, PostgreSQL also requires <strong>USER<\/strong>, PASSWORD, <strong>HOST<\/strong>, and <strong>PORT<\/strong>. These parameters are configured in the <strong>settings.py<\/strong> file, under the <strong>DATABASES<\/strong> section:<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DATABASES = {\n\n&nbsp;&nbsp;&nbsp;&nbsp;'default': {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'ENGINE': 'django.db.backends.postgresql',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'NAME': 'mydatabase',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'USER': 'mydatabaseuser',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'PASSWORD': 'mypassword',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'HOST': 'localhost',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'PORT': '5432',\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>Differences<\/strong> &ndash; unlike SQLite, PostgreSQL is a fully-featured database that supports multiple concurrent users, advanced querying, and transactions. You&rsquo;ll need to install PostgreSQL on your server, create a database and user, and configure more complex settings.<\/li>\n<\/ul><p><strong>MySQL and MariaDB<\/strong><\/p><p>Both are fast and reliable relational databases widely used in web development. MySQL is known for its speed, while MariaDB, a fork of MySQL, focuses on community-driven development and is fully compatible with MySQL.<\/p><p>These databases are excellent for high-traffic web applications and are often favored for their performance.<\/p><ul class=\"wp-block-list\">\n<li><strong>Setup<\/strong> &ndash; MySQL and MariaDB both use the <strong>mysqlclient<\/strong> package to interface with Django.<\/li>\n\n\n\n<li><strong>Configuration<\/strong> &ndash; both use the same parameters as PostgreSQL, which are configured in the<strong> settings.py<\/strong> file under the <strong>DATABASES<\/strong> section:<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DATABASES = {\n\n&nbsp;&nbsp;&nbsp;&nbsp;'default': {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'ENGINE': 'django.db.backends.mysql',&nbsp; # or 'django.db.backends.mariadb' for MariaDB\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'NAME': 'mydatabase',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'USER': 'mydatabaseuser',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'PASSWORD': 'mypassword',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'HOST': 'localhost',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'PORT': '3306',\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>Differences<\/strong> &ndash; Compared to SQLite, MySQL and MariaDB are known for their performance with large datasets and high-traffic web applications. They support multiple storage engines, fast reads, and can handle millions of queries quickly.<\/li>\n<\/ul><p><strong>Oracle and Microsoft SQL Server<\/strong><\/p><p>These enterprise-grade databases offer significant power, especially for large-scale web applications.<\/p><p>However, their setup can be more complex, and they are typically used in specific enterprise environments where the business already relies on Oracle or SQL Server for other software.<\/p><ul class=\"wp-block-list\">\n<li><strong>Setup<\/strong> &ndash; both require additional drivers for integration with Django. For Oracle, you&rsquo;ll need <strong>cx_Oracle<\/strong>, and for SQL Server, you&rsquo;ll need <strong>pyodbc<\/strong>.<\/li>\n\n\n\n<li><strong>Configuration<\/strong> &ndash; each of these systems requires a more complex setup, including server installation, driver installation, and configuring database credentials in the <strong>settings.py<\/strong> file.<\/li>\n\n\n\n<li><strong>Differences<\/strong> &ndash; Oracle and SQL Server offer enterprise-grade features such as advanced transaction handling, optimized performance, and integration with large-scale systems. Their setup is more complex than SQLite and is typically handled by specialized database administrators.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-choosing-the-right-database-for-your-project\">Choosing the right database for your project<\/h3><p>With so many different databases available, how do you choose the right one? Here&rsquo;s a quick, to-the-point breakdown:<\/p><ul class=\"wp-block-list\">\n<li><strong>Development and testing<\/strong> &ndash; stick with SQLite. It&rsquo;s simple, requires no setup, and is ideal for local testing.<\/li>\n\n\n\n<li><strong>Small-scale production<\/strong> &ndash; for smaller, low-traffic web applications, MySQL or MariaDB may be a better choice. They offer better performance than SQLite and are easier to learn than PostgreSQL.<\/li>\n\n\n\n<li><strong>Large-scale production<\/strong> &ndash; PostgreSQL is highly recommended for Django projects that require scalability, security, and advanced features.<\/li>\n\n\n\n<li><strong>Enterprise environments<\/strong> &ndash; if you work in an enterprise setting that already uses Oracle or SQL Server for other applications, these databases are likely the best choice due to integration requirements.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-setting-up-postgresql-with-django\">Setting up PostgreSQL with Django<\/h3><p>In this section, we&rsquo;ll walk through the process of integrating PostgreSQL with Django, as it&rsquo;s one of the most commonly used databases for production applications.<\/p><ol class=\"wp-block-list\">\n<li>To integrate PostgreSQL with Django, you first need to install it on your system:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sudo apt update\n\nsudo apt install postgresql postgresql-contrib<\/pre><ol start=\"2\" class=\"wp-block-list\">\n<li>Django uses the <strong>psycopg2<\/strong> package to interact with PostgreSQL. Install it using <strong>pip<\/strong>:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">pip install psycopg2<\/pre><ol start=\"3\" class=\"wp-block-list\">\n<li>Switch to the PostgreSQL user:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sudo -u postgres psql<\/pre><ol start=\"4\" class=\"wp-block-list\">\n<li>Create a new database:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">CREATE DATABASE mydatabase;<\/pre><ol start=\"5\" class=\"wp-block-list\">\n<li>Create a user with a password:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">CREATE USER mydatabaseuser WITH PASSWORD 'mypassword';<\/pre><ol start=\"6\" class=\"wp-block-list\">\n<li>Grant the user all privileges on the database:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">GRANT ALL PRIVILEGES ON DATABASE mydatabase TO mydatabaseuser;<\/pre><ol start=\"7\" class=\"wp-block-list\">\n<li>Exit the PostgreSQL shell:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\\q<\/pre><ol start=\"8\" class=\"wp-block-list\">\n<li>Open your <strong>settings.py file<\/strong> and locate the <strong>DATABASES<\/strong> section. Modify it for PostgreSQL as follows:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">DATABASES = {\n\n&nbsp;&nbsp;&nbsp;&nbsp;'default': {\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'ENGINE': 'django.db.backends.postgresql',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'NAME': 'mydatabase',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'USER': 'mydatabaseuser',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'PASSWORD': 'mypassword',\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'HOST': 'localhost',&nbsp; # Use '127.0.0.1' if 'localhost' doesn't work\n\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'PORT': '5432', &nbsp; &nbsp; &nbsp; # Default PostgreSQL port\n\n&nbsp;&nbsp;&nbsp;&nbsp;}\n\n}<\/pre><p>The actual <strong>PASSWORD<\/strong> and <strong>USER<\/strong> values should match the ones you set in <strong>Step 5<\/strong>.<\/p><ol start=\"9\" class=\"wp-block-list\">\n<li>Now that your database is configured, apply your project&rsquo;s migrations to set up the necessary tables in PostgreSQL:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python manage.py migrate<\/pre><p>This command will create the required tables in your PostgreSQL database.<\/p><ol start=\"10\" class=\"wp-block-list\">\n<li>Finally, run the Django development server to verify that the PostgreSQL integration is successful:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python manage.py runserver<\/pre><p>Open <strong>http:\/\/127.0.0.1:8000\/<\/strong> in your browser. If the Django welcome page appears without errors, your database connection is working correctly.<\/p><h2 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h2><p>In summary, Django makes working with databases simple and efficient. Its models let you define your database structure using Python, and migrations automatically handle database updates.<\/p><p>For development, SQLite is ideal, but for larger, production-ready projects, PostgreSQL, MySQL, or MariaDB offer better scalability and performance. Don&rsquo;t worry; Django&rsquo;s flexibility ensures your app can scale seamlessly as it grows.<\/p><p>Next, you can start working with <a href=\"\/my\/tutorials\/building-django-views\">Django views<\/a> and <a href=\"\/my\/tutorials\/working-with-django-templates\">templates<\/a> to build dynamic content for your site.<\/p><h2 class=\"wp-block-heading\" id=\"h-django-models-faq\">Django models FAQ<\/h2><div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-694483f8bb5f2\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How do Django models work?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Django models define the database structure using Python classes. Each model corresponds to a database table, and its attributes represent the table&rsquo;s fields. When you run migrations, Django creates or updates the database tables based on your models.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-694483f8bb5f5\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How do I create a Django model?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>To create a Django model, define a class in <strong>models.py<\/strong> that inherits from <strong>django.db.models.Model<\/strong> and specify the fields. Then, run <strong>python manage.py makemigrations<\/strong> and <strong>python manage.py migrate<\/strong> to update the database.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-694483f8bb5f6\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Can I use multiple databases with Django models?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, Django supports multiple databases. You can configure them in<strong> settings.py<\/strong> and use the <strong>using()<\/strong> method to specify which database a query should use.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Django models are the heart of data management in any Django application. They define the structure of your database and serve as the foundation for creating dynamic, data-driven applications. With Django&rsquo;s powerful object-relational mapping (ORM) system, working with models becomes seamless, enabling you to define, query, and manipulate data effortlessly. Let&rsquo;s explore how Django models [&#8230;]<\/p>\n<p><a class=\"btn btn-secondary understrap-read-more-link\" href=\"\/my\/tutorials\/django-models-and-databases\">Read More&#8230;<\/a><\/p>\n","protected":false},"author":185,"featured_media":120144,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"How to work with Django models and databases","rank_math_description":"Learn how Django models work, how to create and migrate them, and explore database options like PostgreSQL for production environments.","rank_math_focus_keyword":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-120137","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"hreflangs":[],"_links":{"self":[{"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/posts\/120137","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/users\/185"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/comments?post=120137"}],"version-history":[{"count":6,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/posts\/120137\/revisions"}],"predecessor-version":[{"id":126021,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/posts\/120137\/revisions\/126021"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/media\/120144"}],"wp:attachment":[{"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/media?parent=120137"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/categories?post=120137"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hostinger.com\/my\/tutorials\/wp-json\/wp\/v2\/tags?post=120137"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}