【问题标题】:factory_boy objects seem to lack primary keysfactory_boy 对象似乎缺少主键
【发布时间】:2013-09-23 15:47:16
【问题描述】:

当我创建 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 documentation,如果我创建一个 User 实例,我应该得到一个“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”属性。但是,我在文档中的任何地方都没有看到这样做,所以我认为这不是你应该做的。

谢谢。

【问题讨论】:

    标签: python django django-models factory-boy


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,mariodev。为了其他人的利益,我可能会补充一下,上面链接中的示例代码似乎不正确。如果你说,“FACTORY_FOR = 'myapp.User',你会得到错误:“AttributeError: 'str' object has no attribute 'object'。”你不应该在 myapp.User 周围加上引号。
    • 一年前就有这个问题,用这个答案解决了。现在回来了,在不同的项目上苦苦挣扎之后,刚刚看到我已经 +1 你了。最终我会学会的!
    【解决方案2】:

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

    user = UserProfile.create()
    

    一旦你使用了 DjangoModelFactory 的子类,它会做同样的事情:

    user = UserProfile()
    

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

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

    user = UserProfile.build()
    

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2017-01-03
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多