July 29, 2026

Nifty Django Feature: setUpTestData

published by Tim Schilling
in blog Better Simple
published date 2026-07-29
original entry Nifty Django Feature: setUpTestData

Full disclosure, I stole this feature from Adam Johnson. I learned it while reading “Speed up your Django Tests”, which I can’t recommend enough. So go buy it!

This feature is using Django’s setUpTestData() method. This method is called once per test class. By creating your test data here rather than in setUp, you reduce the number of create and destroy data operations.

Let’s look at some code.

from django.test import TestCase
from myapp.models import Pet, Species

class PetFuzzinessTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.dog = Species.objects.create(name="Dog")

    def setUp(self):
        self.spot = Pet.objects.create(name="Spot", species=self.dog)

    def test_get_fuzzy(self):
        lady = Pet.objects.create(name="Lady Macbark", species=self.dog)
        self.assertLessThan(self.spot.get_fuzzy(), lady.get_fuzzy())

    def test_boop_factor(self):
        lady = Pet.objects.create(name="Lady Macbark", species=self.dog)
        self.assertEqual(self.spot.boopiness(), lady.boopiness())

If we run both tests for PetFuzzinessTests, the lady instances will be created and destroyed twice. Once in each individual test method. The spot instance will also be created and destroyed twice. This is because setUp is called once for each test and there are two tests.

However, the dog instance will only be created and destroyed once. This is because setUpTestData is called just once regardless of how many test methods are on the class.

So if you find your tests are running a bit slow, consider using setupTestData to speed them up.


If you have thoughts, comments, or questions, please let me know. You can set up a meeting with me, or find me on the Fediverse, Django Discord server or use email.