Python Django ORM In a Nutshell
Setting Up Django ORM
Before we dive in, let’s set up Django in a project. If you haven’t installed Django yet, do this:
|
|
Then, create a new Django project:
|
|
Now, go to settings.py
and configure your database. By default, Django uses SQLite, but you can change it to PostgreSQL, MySQL, or whatever suits your fancy.
Example for PostgreSQL:
|
|
Defining Models (A.K.A Your Database Tables)
In Django, a model is a Python class that represents a database table. You define your models in models.py
inside your app.
|
|
What’s happening here?
Author
andBook
are two tables.CharField
,EmailField
, andDateField
define the types of data these fields hold.ForeignKey
sets up a relationship between books and authors.__str__()
makes Django display readable names in the admin panel.
Run migrations to apply these models to your database:
|
|
Boom! Your database is now ready to store authors and books.
Querying Data (The Fun Part)
Alright, let’s talk about CRUD—Create, Read, Update, and Delete. This is where Django ORM really shines.
Creating Data
Adding new records is as easy as pie:
|
|
Reading Data
Fetching data? Piece of cake.
|
|
Updating Data
Want to update a book’s title? No problem.
|
|
Deleting Data
Deleting is just as easy:
|
|
Just like that, no more Harry Potter in the database. (Oops!)
Django ORM vs Raw SQL
If you’re wondering how Django ORM compares to raw SQL, check out this handy table:
Feature | Django ORM | Raw SQL |
---|---|---|
Readability | Super clean and Pythonic | SQL can be verbose and complex |
Performance | Optimized but slightly abstracted | Fine-tuned control |
Security | Built-in protection against SQL injection | Requires manual handling |
Portability | Works across multiple databases | Tied to a specific SQL dialect |
Flexibility | Limited to ORM’s capabilities | Total control |
Django ORM is great for most cases, but if you need super complex queries, raw SQL might still be your best bet.
Running Raw SQL in Django ORM
Sometimes, ORM doesn’t cut it, and you need to write raw SQL. You can do that like this:
|
|
Use with caution—raw SQL is powerful but also dangerous if you’re not careful!
Key Ideas Table
Concept | Summary |
---|---|
Django ORM | A way to interact with databases using Python classes instead of raw SQL |
Models | Represent database tables using Python classes |
Queries | CRUD operations (Create, Read, Update, Delete) using Pythonic syntax |
Migrations | Django’s way of applying database changes automatically |
Raw SQL | Can be used when ORM isn’t enough, but should be used carefully |