Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

G is for get_or_create - Python A to Z

Code in this blog post was written with versions: Python: 3.14

Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.

Let’s take our first journey into the wonders of Django, my favourite web backend. One of the reasons I love it is its ORM which we’ll talk a bit more when we reach the midway of the month and letter O.

Today, I want to show my appreciation for one of the methods in QuerySet: get_or_create which allows you to query for a specific item and if it doesn’t exist, it creates it.

# Imagine we have a Card model
from .models import Card

pikachu_25, created = Card.objects.get_or_create(
      name='Pikachu', number=25
  )

Here, get_or_create queries for a Card with name of Pikachu and number of 25. If it finds one, it returns a tuple of (card_found, False) . If one does not exist, it returns a tuple of (new_card, True). The second value in the return tuple indicates whether a new object was created or not.

I especially love using it in my data entry scripts / custom Django commands. I read data from a JSON file or an API and my models have a bunch of connections to each other.

For example, a Pokémon TCG card in this example belongs to a Set. If I read in 100 cards and they come from 5 different sets, get_or_create lets me easily create the sets that are missing and reuse the ones that exist.

Right now, when my script creates a Card object in the database during data input, there are 13 such relationships with different things. The codebase looks so much neater and easier to follow thanks to get_or_create.


If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.