django - Factoryboy 无法生成依赖数据库的字段
问题描述
我使用django-cities-light来存储用户位置。但是,我需要将庞大的国家和城市数据集导入数据库。
我使用Factory
类在网站上测试和创建虚拟数据。
如何创建一个在测试期间自动填充这些字段的工厂?
不测试时,工厂正常工作Country.objects.all()
。但是在测试的时候,数据库是空的,找不到任何国家:IndexError: Cannot choose from an empty sequence
.
对于这种情况,正确的方法应该是什么?如果您对下面使用 LazyAttributes 有更好的解决方案,请告诉我更好的方法。
class UserProfileFactory(DjangoModelFactory):
class Meta:
model = UserProfile
# ...
birth_country = FuzzyChoice(Country.objects.all()) or None
birth_region = factory.LazyAttribute(
lambda o: o.birth_country.region_set.order_by("?").first()
)
birth_subregion = factory.LazyAttribute(
lambda o: o.birth_region.subregion_set.order_by("?").first()
)
birth_city = factory.LazyAttribute(
lambda o: o.birth_region.city_set.order_by("?").first()
)
解决方案
推荐阅读
- android - 如何在 ARCORE 中更改锚点的大小和颜色?
- vhdl - 有限状态机模拟在modelsim上无法正常工作
- swift - 添加 ViewModel 后,SwiftUI 视图未在按钮切换上更新
- xpath - 找不到动态 Xpath 元素
- c# - 将字符串或列表转换为 Renci.SshNet.Sftp
- apache - 通过 Zuul 路由 HTTP 静态内容请求
- authentication - 有没有办法将另一个用户添加到我的帐户?
- php - 如何检查 SQLite 行是否为空
- python - Python Bytecode + LOAD_NAME 按值还是按名称?
- c - 如何使用证书的根 ca 信任列表(即 json 数组)验证公共证书