w3resource

Configuring and using SQLite in Django Projects


Using SQLite with Django

Django, a popular Python web framework, uses SQLite as its default database. SQLite’s simplicity and serverless nature make it an excellent choice for small to medium-sized applications and rapid development. This guide elaborates on configuring and using SQLite in a Django project, covering installation, setup, and basic operations.


Setting Up SQLite in Django

1. Installing Django

Before using SQLite with Django, ensure Django is installed. You can install it using pip:

pip install django

2. Creating a Django Project

Create a new Django project and set SQLite as the database backend.

django-admin startproject myproject

Navigate to the project directory:

cd myproject

3. Configuring SQLite in settings.py

Django automatically configures SQLite as the database in the settings.py file.

Code:

# settings.py in the Django project

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # Database engine
        'NAME': BASE_DIR / 'db.sqlite3',        # Database file path
    }
}

Explanation:

  • ENGINE: Specifies the database backend, here SQLite.
  • NAME: Points to the SQLite database file (stored in the project directory).

4. Running Initial Migrations

Run the following commands to initialize the database and create the required tables for Django's built-in apps:

Code:

python manage.py migrate

Explanation:

  • This command applies all pending migrations, creating the database and required tables.

Using SQLite with Django Models

1. Defining a Model

Create a model in one of your apps to define the database schema.

Code:

# models.py in a Django app

from django.db import models

class Employee(models.Model):
    name = models.CharField(max_length=100)  # Employee name
    department = models.CharField(max_length=100)  # Department name
    salary = models.DecimalField(max_digits=10, decimal_places=2)  # Salary

Explanation:

  • Models define the structure of your database tables.
  • Each field corresponds to a column in the table.

2. Making Migrations

Generate and apply migrations for the defined model:

Code:

# Generate migrations
python manage.py makemigrations

# Apply migrations to the database
python manage.py migrate

Explanation:

  • makemigrations: Creates a migration file based on your model changes.
  • migrate: Applies the migration to the database, creating or altering tables.

3. Interacting with SQLite via Django

Adding Data

Code:

# Django shell
python manage.py shell

# Import the model
from myapp.models import Employee

# Create a new Employee record
Employee.objects.create(name='Alice', department='HR', salary=55000.00)

Querying Data

Code:

# Fetch all employee records
employees = Employee.objects.all()

# Print each employee's name
for employee in employees:
    print(employee.name)

Updating Data

Code:

# Update an employee's salary
employee = Employee.objects.get(name='Alice')
employee.salary = 60000.00
employee.save()

Deleting Data

Code:

# Delete an employee record
employee = Employee.objects.get(name='Alice')
employee.delete()

Explanation:

  • Django's ORM (Object-Relational Mapping) simplifies database operations.
  • Queries like create, get, all, and delete provide an abstraction over raw SQL.

Testing the SQLite Database in Django

Django automatically creates a test SQLite database during testing. You can run tests using:

Code:

python manage.py test

Explanation:

  • Tests are run on a temporary SQLite database that is destroyed after the tests finish.

Advantages of Using SQLite in Django

    1. Ease of Setup: Preconfigured and requires minimal setup.

    2. Zero Dependencies: No additional installation or server configuration.

    3. Lightweight: Ideal for development and small-scale applications.

    4. Cross-Platform: Supported across various environments.


Common Challenges and Solutions

    1. Database Locking Issues

    SQLite locks the database during write operations. Use transactions or Django's ORM to manage concurrency.

    2. Migrating to Other Databases

    SQLite is not ideal for large-scale applications. Use Django's dumpdata and loaddata commands to migrate data to a more robust database like PostgreSQL.

Practical Guides to SQLite Snippets and Examples.



Follow us on Facebook and Twitter for latest update.