Last active
July 26, 2022 00:51
-
-
Save ryu22e/238e8c2c5f8d26f6eb95c85aaca73b6c to your computer and use it in GitHub Desktop.
Django + factory_boyでクエリ発行回数を減らすには
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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