gpt4 book ai didi

python - 如何让 DjangoModelFactory 创建模型而不将其保存到数据库?

转载 作者:行者123 更新时间:2023-12-04 14:45:41 25 4
gpt4 key购买 nike

我正在 Django 项目中编写单元测试。我有一个工厂可以使用 .create() 创建对象方法。所以在我的单元测试中,我使用了这个:

device = DeviceFactory.create()

不过,这总是会在数据库中创建一条记录。有没有办法让工厂创建一个对象而不将它保存到数据库中?

我查看了文档,但找不到。我错过了什么吗?

最佳答案

报价 this bit of the documentation , 使用 .build()而不是 .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()

关于python - 如何让 DjangoModelFactory 创建模型而不将其保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com