首页 > 解决方案 > 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()
    )

标签: djangopytestfactory-boy

解决方案


推荐阅读