The problem (not evidenced in the simplified example) was an attempt to call the factory in the definition of another factory:
class BarFactory(factory.Factory):
FACTORY_FOR = models.Bar
spam = FooFactory(code=34)
That fails with django.db.utils.DatabaseError: no such table: foo_foo
, because the call is made when Django's test runner is importing the unit test module. At that point, none of the models are in the database.
Instead, any calls to the factories must wait until the tests are run, not when the classes are defined. In this case:
class BarFactory(factory.Factory):
FACTORY_FOR = models.Bar
spam = factory.SubFactory(FooFactory)
…
class BarTestCase(TestCase):
def setUp(self):
""" Set up test fixtures. """
self.test_foo = FooFactory(code=34)
def test_frobnicates_to_spanguloid(self):
""" The instance should frobnicate to a spanguloid. """
test_bar = BarFactory(foo=self.test_foo)