我用虚拟数据填充我的数据库,我有单独的个人资料,用户,图片模型。如何连接它们以使用相同的用户?
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为每个用户
1条答案
按热度按时间unguejic1#
您可以使用FactoryBoy的反向依赖项为每个用户创建它们,而不是通过Profile的子工厂
这看起来像这样: