如何分配 SubFactory 的属性而不是 SubFactory 本身

How to assign the attribute of SubFactory instead of the SubFactory itself

我需要 SubFactory 的属性而不是它创建的对象。

# models.py
class User:
    pass

class UserProfile:
    user = models.OneToOneField(User)

class Job:
    user = models.ForeignKey(User)


# factories.py
class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

class UserProfileFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = UserProfile

    user = factory.SubFactory(UserFactory)

class JobFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Job

    # for certain reasons, I want to use UserProfileFactory here but get the user generated from it
    user = factory.SubFactory(UserProfileFactory).user  # doesn't work but you get the idea

我采用了以下可能对某些人有用的方法:

user = factory.LazyFunction(lambda: UserProfileFactory().user)

也就是说,没有记录这是否是使用工厂的合法方式,所以如果这是错误的,请随时纠正。

最好的方法是结合class Params and factory.SelfAttribute:


class JobFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Job

    class Params:
        profile = factory.SubFactory(ProfileFactory)

    user = factory.SelfAttribute("profile.user")

参数在工厂内部使用,但在调用模型之前被丢弃。

这样:

  • 如果身边有资料可以提供给工厂:JobFactory(profile=foo)
  • 您可以设置个人资料用户的一些子字段:JobFactory(profile__user__username="john.doe")