django 工厂男孩将模型连接到现有用户

lx0bsm1f  于 2023-05-08  发布在  Go
关注(0)|答案(1)|浏览(108)

我用虚拟数据填充我的数据库,我有单独的个人资料,用户,图片模型。如何连接它们以使用相同的用户?

class UserFactory(DjangoModelFactory):

    class Meta:
        model = User

    email = factory.Faker('email')
    first_name = factory.Faker('first_name')
    birthday = factory.Faker('date_object')
    age = factory.Faker('pyint', min_value=18, max_value=100)
    is_staff = False
    is_active = True

class UserPhotoFactory(DjangoModelFactory):

    class Meta:
        model = UserPhoto

    user = factory.RelatedFactory(UserFactory) #????
    order = factory.Faker('pyint', min_value=0, max_value=4)
    url = factory.Faker(
        'random_element', elements=[x for x in ['https://picsum.photos/seed/picsum/200/300', 'https://picsum.photos/seed/pssss/200/300', 'https://picsum.photos/seed/picwum/200/300']]
    )

class ProfileFactory(DjangoModelFactory):

    class Meta:
        model = Profile
    
    user = factory.SubFactory(UserFactory)
    bio = factory.LazyAttribute(lambda o: FAKE.paragraph(nb_sentences=5, ext_word_list=['abc', 'def', 'ghi', 'jkl']))

在这种情况下我调用shell

ProfileFacotry.create_batch(10)

这就创建了用户和他们相应的配置文件。现在我想添加UserPhoto到通过ForeignKey与USER相关的混合中,如下所示

class UserPhoto(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    order = models.PositiveIntegerField(null=True)
    url = models.CharField(max_length=220)

我想实现的是获得10个用户10个配置文件,让说20张图片2为每个用户

unguejic

unguejic1#

您可以使用FactoryBoy的反向依赖项为每个用户创建它们,而不是通过Profile的子工厂
这看起来像这样:

class UserFactory(DjangoModelFactory):

    class Meta:
        model = User

    email = factory.Faker('email')
    first_name = factory.Faker('first_name')
    birthday = factory.Faker('date_object')
    age = factory.Faker('pyint', min_value=18, max_value=100)
    is_staff = False
    is_active = True

    profile = factory.RelatedFactory(
        ProfileFactory,
        factory_related_name = 'profile',
        action=models.Profile.ACTION_CREATE,
    )

    image1 = factory.RelatedFactory(
        UserPhotoFactory,
        factory_related_name = 'user_photo',
        action=models.Profile.ACTION_CREATE,
    )

    image2 = factory.RelatedFactory(
        UserPhotoFactory,
        factory_related_name = 'user_photo',
        action=models.Profile.ACTION_CREATE,
    )

相关问题