How to let DjangoModelFactory create a model without saving it to the DB?
Asked Answered
C

1

12

I'm writing unit tests in a Django project. I've got a factory to create objects using the .create() method. So in my unit tests I'm using this:

device = DeviceFactory.create()

This always creates a record in the DB though. Is there a way that I can make the factory create an object without saving it to the DB yet?

I looked over the documentation but I can't find it. Am I missing something?

Cornela answered 4/11, 2019 at 15:54 Comment(0)
T
26

Quoth this bit of the documentation, use .build() instead of .create():

# Returns a User instance that's not saved
user = UserFactory.build()

# Returns a saved User instance.
# UserFactory must subclass an ORM base class, such as DjangoModelFactory.
user = UserFactory.create()

# Returns a stub object (just a bunch of attributes)
obj = UserFactory.stub()

# You can use the Factory class as a shortcut for the default build strategy:
# Same as UserFactory.create()
user = UserFactory()
Thursby answered 4/11, 2019 at 16:6 Comment(1)
Haha, happens to the best of us. :)Thursby

© 2022 - 2024 — McMap. All rights reserved.