Django offers ORM (Object Relational Mapping) which lets you run SQL queries in a pythonic way.
SQL:
SELECT * FROM Reporter;
Django
Reporter.objects.all()
Why we should use ORM instead of raw SQL queries?
Developers of Django made sure that if we use built-in ORM, we will not become the victims of SQL Injection attacks. Using the raw SQL queries there's a high chance some hackers may do the SQL Injections attacks.
Things to remember:
Say we have this type of Project structure with the below models and the django default migrations have been migrated:
.
├── core
│ ├── __init__.py
│ ├── __pycache__
│ ├── asgi.py
│ ├── models.py
│ ├── settings.py
│ ├── urls.py
│ ├── views.py
│ └── wsgi.py
├── db.sqlite3
└── manage.py
# core.models.py
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
def __str__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
- After making some edits to the core/models.py, run
python3 manage.py makemigrations core
python3 manage.py migrate
We should always specify which app the migrations should be made to.
- __startswith
>>> Reporter.objects.get(full_name__startswith="Jo")
<Reporter: John Smith>
- __contains
>>> Reporter.objects.get(full_name__contains='John')
<Reporter: John Smith>
- Foreign key
>>> r = Reporter.objects.get(id=1)
>>> a = Article(pub_date=date.today(), headline="ORM", content="Hello", reporter=r)
>>> a.reporter
'John Smith'
>>> r.article_set.all()
<QuerySet [<Article: ORM>]>
- filter(pub_date__year)
>>> date.today().year
2025
>>> Article.objects.filter(pub_date__year=date.today().year)
<QuerySet [<Article: ORM>]>
Top comments (0)