Skip to content

Instantly share code, notes, and snippets.

@ryu22e
Last active July 26, 2022 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryu22e/238e8c2c5f8d26f6eb95c85aaca73b6c to your computer and use it in GitHub Desktop.
Save ryu22e/238e8c2c5f8d26f6eb95c85aaca73b6c to your computer and use it in GitHub Desktop.
Django + factory_boyでクエリ発行回数を減らすには
from django.test import TestCase
from .factories import ExampleFactory
from .models import Example
class ExampleTest(TestCase):
def test_example_1(self):
# これだとループの回数分INSERT文を発行する(なるべく避けたい書き方)
for i in range(3):
ExampleFactory()
self.assertEqual(Example.objects.count(), 3)
def test_example_2(self):
# create_batchメソッドだとINSERT文1回でsize分のデータを作れる
ExampleFactory.create_batch(size=3)
self.assertEqual(Example.objects.count(), 3)
def test_example_3(self):
# create_batchメソッドは引数でフィールドの値の指定もできる
ExampleFactory.create_batch(title='HELLO', size=3)
self.assertEqual(Example.objects.count(), 3)
def test_example_4(self):
# 各データごとにフィールドの値を変えたいなら、buildメソッドを使う
examples = (
ExampleFactory.build(title=f'HELLO{i}')
for i in range(3)
)
Example.objects.bulk_create(examples)
self.assertEqual(Example.objects.count(), 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment