当我创建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'属性。但是,我在文档中的任何地方都看不到此操作,因此我认为这不是您应该执行的操作。
谢谢。
最佳答案
为了支持django,您需要使用DjangoModelFactory
:
https://factoryboy.readthedocs.org/en/latest/orms.html#the-djangomodelfactory-subclass
关于python - factory_boy对象似乎缺少主键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18963526/