FactoryBoy "create" strategy doesn't seem to save django model

1.6k views Asked by At

Probably a silly question, but I've been banging my head against a wall for a little while now. I decided to try factory-boy library to simplify my tests and defined a factory:

from . import models
import factory

class QualtricsSurveyCacheFactory(factory.Factory):
class Meta:
    model = models.QualtricsSurveyCache

survey_id = "SR_1234"
qualtrics_username = "[email protected]#bla"
survey_name = "fake"

However, when I do QualtricsSurveyCacheFactory.create() it returns model with id = None

>>> survey = QualtricsSurveyCacheFactory()
>>> print survey.id
None

I can .save() model after creation, but just curious why it doesn't do it automatically.

1

There are 1 answers

0
wim On BEST ANSWER

You weren't using the correct base class for Django models. Inherit instead from:

class QualtricsSurveyCacheFactory(factory.DjangoModelFactory):    
    ...

Then, QualtricsSurveyCacheFactory() will return a saved instance with a primary key. Use QualtricsSurveyCacheFactory.build() if you want an unsaved instance.