Django Databases - SQLite and ORM


Introduction

Django uses databases to store and manage data for web applications. By default, Django comes with an SQLite database and provides a powerful Object-Relational Mapping (ORM) system to interact with it. In this guide, we'll explore Django databases, SQLite, and ORM.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Django: You should have Django installed. If not, use pip install django to install it.
  • Django Project: You should have a Django project set up. If not, refer to the guide on creating your first Django project.

SQLite Database

Django uses SQLite as the default database for development. SQLite is a lightweight, file-based database, making it easy to get started without complex database setups.


Defining Models

In Django, you define your database structure using models. Models are Python classes that map to database tables. Each model represents a table, and class attributes represent table fields.


Sample Code

Create a Django model in your app's models.py file. For example:

from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=2)

Using the ORM

Django's ORM allows you to interact with the database using Python code. You can create, retrieve, update, and delete records without writing raw SQL queries.


Sample Code

You can use the ORM to query the database, like retrieving all products:

from myapp.models import Product
# Retrieve all products
products = Product.objects.all()

Conclusion

Django databases, SQLite, and ORM provide a robust system for managing data in web applications. By defining models and using the ORM, you can create and manipulate database records efficiently and maintain the integrity of your application's data.