Build database-backed applications using Django's powerful built-in ORM. Learn to define models, use Django's admin interface, perform queries with the QuerySet API, and leverage Django's migrations system - perfect for full-stack data applications.
For Django, we need to set up a minimal Django project structure. We need to create a new directory and add the following files:
django_orm_example/
├── manage.py
├── myproject/
│ ├── **init**.py
│ ├── settings.py
│ └── models.py
└── run_example.py
The example demonstrates how to:
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'your-secret-key' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'myproject', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } USE_TZ = True
This file configures the Django project, including the database settings (SQLite in this case) and installed apps.
from django.db import models class User(models.Model): username = models.CharField(max_length=50, unique=True) email = models.EmailField(unique=True) def __str__(self): return f"User: {self.username}, Email: {self.email}"
Here, we define the User model with two fields: username and email. The __str__ method provides a string representation of the object.
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
The manage.py file is a command-line utility that lets you interact with your Django project in various ways. It's automatically created in each Django project.
Key points about manage.py:
It sets up the Django environment by specifying the settings module.
It provides a way to run Django management commands. For example:
python manage.py runserver to start the development serverpython manage.py makemigrations to create new migrationspython manage.py migrate to apply migrationsIt handles exceptions if Django isn't installed or can't be imported.
While not used directly in our ORM example, it's crucial for many Django development tasks and would be used in a full Django application.
In a typical Django workflow, you'd use manage.py for tasks like creating database tables (python manage.py migrate), but our example script (run_example.py) bypasses this for simplicity.
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") import django django.setup() def run_example(): from django.db import connection from myproject.models import User # Ensure the model table is created with connection.schema_editor() as schema_editor: schema_editor.create_model(User) try: new_user = User(username='jane_doe', email='jane@example.com') new_user.save() user = User.objects.get(username='jane_doe') print(user) except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": run_example() print(f"SQLite database created at: {os.path.abspath('db.sqlite3')}")
This script demonstrates:
manage.py file is Django's command-line utility for administrative tasks, but it's not used directly in this example.django-admin startproject.It is generally considered good practice in Python to have all imports at the top of the module. However, in this specific case with Django, there's a particular reason why the imports need to be structured this way. Let's break it down:
The reason for this structure is that django.setup() configures Django's settings and initializes various components. Without this setup, Django-specific imports will fail because the Django environment isn't properly configured yet.
Install Django:
pip install django
Run migrations:
python manage.py migrate
Run the example:
python run_example.py
The script will create a SQLite database file, add a user to it, retrieve and print the user's information, and then display the location of the created database file.