"StopIteration" 在 django setUp() unittest 中使用 factory_boy 时出现异常

"StopIteration" exception while using factory_boy in django setUp() unittest

我有以下工厂:

class ContactFactory(DjangoModelFactory):
    name = Faker('company')
    industry = Iterator(Industry.objects.all())

    class Meta:
        model = 'sales.contact'

    @post_generation
        def requested_devices(self, create, extracted, **kwargs):
            if create:
              self.requested_devices.add(MSize.objects.first())

我正在尝试编写一个测试,例如:

class TestUserCanAskQuestion(TestCase):
    @classmethod
    def setUpTestData(cls):
        call_command('insert_initial_data')

    def setUp(self):
        self.contact = ContactFactory()

但每次我 运行 测试时,都会导致 "StopIteration" 错误。 这是完整的堆栈跟踪:

ERROR: test_dummy (comminquiry.tests.test_views.TestUserCanAskQuestion)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/mnt/c/Users/Alire/Projects/mm/mm-bpmui/src/comminquiry/tests/test_views.py", line 32, in test_dummy
    a = ContactFactory.build()
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/base.py", line 546, in build
    return cls._generate(enums.BUILD_STRATEGY, kwargs)
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/base.py", line 500, in _generate
    return step.build()
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/builder.py", line 272, in build
    step.resolve(pre)
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/builder.py", line 221, in resolve
    self.attributes[field_name] = getattr(self.stub, field_name)
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/builder.py", line 375, in __getattr__
    extra=context,
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/declarations.py", line 196, in evaluate
    value = next(iter(self.iterator))
  File "/mnt/c/Users/Alire/Projects/mm/venv/lib/python3.5/site-packages/factory/utils.py", line 136, in __iter__
    value = next(self.iterator)
StopIteration

----------------------------------------------------------------------
Ran 1 test in 2.433s

如果我将 ContactFactory() 移到 class 之外,错误就会消失。 我错过了什么?还是 factory boy 或 django 中的错误?

(我正在使用 factory_boy==2.11.1 和 django==2.1.2)

正如@dirkgroten 所建议的,其中一个字段返回一个空查询集。这是错误的根本原因。