Django ORM basics

16 Nov 2020

category is ~ django ~ django orm ~ database ~ python ~

This post will be continuously updated!

Since starting my current job, I've found I need to brush up a bit on querysets and ORM (object-relational mapping). A queryset is a Python object that lets you view (Django) model instances through various filters or conditions. I thought it was enough to see the number of instances, get one, or get them in a certain order. But there's so much more to it than that.

Django ORM is so useful primarily for two reasons:

  1. It prevents you from having to make raw SQL queries on your database — i.e. not touching the database, just having a look at what's in there.
  2. In very large applications, filtering and using managers prevents you from having to query the whole database, or all the instances of a model — two ways to significantly reduce performance.

It can be a little finicky to implement from memory. But then again, it's about understanding concepts, not ultimate knowledge.

Here are a few queryset examples, using the BlogPage class from this very blog. It's just a fraction of what's out there, but you can find out more in the official docs.

⟵ return to blog