9

当我创建 factory_boy 对象时,该对象似乎没有主键,我不知道为什么。这是我的模型和工厂:

# models.py
from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    # UserProfile is a subset table of User.  They have a 1:1 relationship.
    user = models.ForeignKey(User, unique=True)
    gender = models.CharField(max_length=1)

# factories.py
import factory
from django.contrib.auth.models import User
from .models import UserProfile

class UserFactory(factory.Factory):
    FACTORY_FOR = User
    username = 'jdoe'

class UserProfileFactory(factory.Factory):
    FACTORY_FOR = UserProfile
    user = factory.lazy_attribute(lambda a: UserFactory())
    gender = 'M'

现在根据有关关联的 factory_boy文档,如果我创建一个用户实例,我应该得到一个“id”字段。但是,我没有。这就是我得到的(在解释器中):

>>> from app.factories import UserFactory, UserProfileFactory
>>> user = UserFactory()
>>> user.username  # This result is correct
'jdoe'
>>> user.id is None   # User should be 'saved' and so this should return False
True

相似地:

>>> user_profile = UserProfileFactory()
>>> user_profile.gender   # This is OK
'M'
>>> user_profile.user     # This is OK
<User: jdoe>
>>> user_profile.id is None  # Why isn't this False?
True

文档说这些 user.id 和 user_profile.id 命令应该返回“False”而不是“True”,因为我正在创建(而不是构建)factory_boy 实例。我在这里想念什么?为什么我在创建这些实例时没有获得“id”值?似乎我可以获得 id 的唯一方法是在我的工厂中显式创建一个“id”属性。但是,我在文档中的任何地方都没有看到这样做,所以我认为这不是你应该做的。

谢谢。

4

2 回答 2

19

对于 django 支持,您需要使用DjangoModelFactory

https://factoryboy.readthedocs.org/en/latest/orms.html#the-djangomodelfactory-subclass

于 2013-09-23T17:09:32.103 回答
4

为了完整起见,还值得注意的是,为了将工厂显式保存到数据库中,文档说您可以使用:

user = UserProfile.create()

一旦您使用 DjangoModelFactory 的子类,它会执行与以下相同的操作:

user = UserProfile()

只有当对象被保存到数据库时,它们才会收到 PK。

要创建工厂并明确不将其保存到数据库,请使用:

user = UserProfile.build()
于 2013-10-29T16:56:39.370 回答