Since ORMs are perfectly fine for 95.523% of use cases.
(Yep, that's the accurate stat).
(Not made up, I swear :-P)
or
are better titles for this talk.
Some also treats save and updates the same way.
Ease M2M relations.
SELECT b.name FROM books b
JOIN authors a ON b.author_id = a.id
WHERE b.title = 'NoORM'
book = Book.objects.select_related().filter(title='NoORM')
# book.author
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String)
isbn = Column(String(13))
author = relationship("Author", backref="book")
Provides a "contract" for developers.
IDEs can auto-complete.
No need to consult db structure.
class Article(models.Model):
...
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date:
raise ValidationError({
'pub_date': _('Draft entries may not have a publication date.')
})
...
class Article(models.Model):
...
def publish(self):
self.status = 'published'
self.pub_date = datetime.now()
...
Chaining (vs. hacks to build the SQL statement)
qs = Article.objects.all()
if start:
qs = qs.filter(pub_date__gte=start)
if search:
qs = qs.filter(title__icontains=search)
if sort_by in ('title', 'pub_date'):
qs = qs.order_by(sort_by)
...
This is something Non-Relational DBs got right.
Usually one provides a dict, which is easy to construct.
Schema & Data
What if you fall in the other 4.477% ?
ORMs try to map in memory data structures to relational database.
That's a hard problem.
You finally got the complex CTE query right.
Translating to ORM is not always easy.
You've outgrown the use cases which ORM fits perfectly:
While providing de/serialization and validation:
Bonus: easier unit testing without DB mocks.