DEV Community

Erlan Akbaraliev
Erlan Akbaraliev

Posted on

Django Models

Django offers ORM (Object Relational Mapping) which lets you run SQL queries in a pythonic way.

SQL:

SELECT * FROM Reporter;
Enter fullscreen mode Exit fullscreen mode

Django

Reporter.objects.all()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode
  1. After making some edits to the core/models.py, run
python3 manage.py makemigrations core
python3 manage.py migrate
Enter fullscreen mode Exit fullscreen mode

We should always specify which app the migrations should be made to.

  1. __startswith
>>> Reporter.objects.get(full_name__startswith="Jo")
<Reporter: John Smith>
Enter fullscreen mode Exit fullscreen mode
  1. __contains
>>> Reporter.objects.get(full_name__contains='John')
<Reporter: John Smith>
Enter fullscreen mode Exit fullscreen mode
  1. 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>]>
Enter fullscreen mode Exit fullscreen mode
  1. filter(pub_date__year)
>>> date.today().year
2025
>>> Article.objects.filter(pub_date__year=date.today().year)
<QuerySet [<Article: ORM>]>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)