A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-django-integration.php below:

Website Navigation


Integrate PostgreSQL with Django: Complete Setup and Usage Guide

Integrate PostgreSQL with Django: Complete Setup and Usage GuideLast update on December 23 2024 07:38:51 (UTC/GMT +8 hours)

PostgreSQL with Django: Setup and Usage Guide

Django, a high-level Python web framework, makes it easy to build secure and scalable applications, while PostgreSQL serves as a powerful, reliable relational database for handling complex data structures. Integrating PostgreSQL with Django provides a robust, flexible environment for web development. This guide will walk you through setting up and using PostgreSQL as the backend database for your Django project, covering configuration, models, migrations, and basic queries.

Step 1: Install Required Packages

First, ensure both Django and the PostgreSQL adapter for Python (psycopg2) are installed:

pip install django psycopg2

Step 2: Configure Django to Use PostgreSQL

In your Django project’s settings file (settings.py), update the DATABASES setting to configure PostgreSQL as the database.

Code:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',  # Specify PostgreSQL as the database
        'NAME': 'your_db_name',                     # Name of your PostgreSQL database
        'USER': 'your_db_user',                     # PostgreSQL username
        'PASSWORD': 'your_password',                # PostgreSQL password
        'HOST': 'localhost',                        # Database server address
        'PORT': '5432',                             # Default PostgreSQL port
    }
}

Step 3: Create Models for Your Django App

Create a model that Django will use to generate tables in PostgreSQL.

Code:


# models.py in your Django app
from django.db import models
# Define a simple model for a 'Customer' table
class Customer(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Step 4: Run Migrations to Create Tables in PostgreSQL

Django uses migrations to apply model changes to the database schema. Run the following commands to create and apply migrations.

Code:


# Generate migration files based on models
python manage.py makemigrations

# Apply migrations to the database
python manage.py migrate

Step 5: Using Django’s ORM to Interact with PostgreSQL

With your models set up and migrated, you can interact with PostgreSQL through Django's ORM.

Insert Data

Code:


# Insert a new customer record
from yourapp.models import Customer

new_customer = Customer(first_name=" Kris ", last_name="Taaniel", email="[email protected]")
new_customer.save()

Query Data

Code:

# Retrieve all customers
customers = Customer.objects.all()
for customer in customers:
    print(customer.first_name, customer.last_name)

Filter Data

Code:


# Filter customers by email
customer = Customer.objects.filter(email="[email protected]").first()
print(customer)

Explanation of Code:

Additional Tips:

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4