列表子工厂元素内的随机模型值
我找不到我的问题的答案。问题是我想生成一个用户工厂模型,其中内部将是一个带有地址的子工厂列表。每个地址元素必须具有不同/随机值(我的意思是每个元素都有不可重复的唯一值)。
在我当前的实现中,所有元素都具有相同的值(也许需要播种?)
实际代码:
from pydantic import BaseModel
from factory import Factory, List, Subfactory
class Address(BaseModel):
Name: str
class User(BaseModel):
Addresses: list[Address]
class AddressFactory(Factory):
Name = fake.name()
class Meta:
model = Address
class UserFactory(Factory):
Addresses = List([SubFactory(AddressFactory) for _ in range(3)])
class Meta:
model = User
实际输出:
> UserFactory()
> User(Addresses=[Address(Name='Isa Merkx'), Address(Name='Isa Merkx'), Address(Name='Isa Merkx')])
所需输出:
> UserFactory()
> User(Addresses=[Address(Name='Isa Merkx'), Address(Name='John Smith'), Address(Name='Elon Musk')])
I cannot find an answer to my question. The thing is that I want to generate an User factory model where inside will be a subfactory List with Addresses. Each Addresses element must have different/random values (I mean that each element has non-repeatable unique values).
In my current implementation, all of the elements have the same values (maybe seeding is necessary?)
Actual code:
from pydantic import BaseModel
from factory import Factory, List, Subfactory
class Address(BaseModel):
Name: str
class User(BaseModel):
Addresses: list[Address]
class AddressFactory(Factory):
Name = fake.name()
class Meta:
model = Address
class UserFactory(Factory):
Addresses = List([SubFactory(AddressFactory) for _ in range(3)])
class Meta:
model = User
Actual output:
> UserFactory()
> User(Addresses=[Address(Name='Isa Merkx'), Address(Name='Isa Merkx'), Address(Name='Isa Merkx')])
Desired Output:
> UserFactory()
> User(Addresses=[Address(Name='Isa Merkx'), Address(Name='John Smith'), Address(Name='Elon Musk')])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
LazyAttribute
每次获取不同的值。输出:
You should use the
LazyAttribute
to get a different value each time.The output:
在您提供的代码中,您必须将
fake.name()
替换为Faker("name")
,其中Faker
是从 < code>factory 在文件的开头。事实上,
fake.name()
仅在定义类时调用一次,而您希望每次实例化工厂时都调用一次。您会找到问题的更详细答案 此处。
In the code you provided, you have to replace
fake.name()
byFaker("name")
, whereFaker
is imported fromfactory
at the beginning of your file.Indeed,
fake.name()
is called only once, when the class is defined, whereas you want it to happen each time you instantiate a factory.You'll find a more detailed answer to your question here.