Factoryboy can not generate database-dependent field

I use django-cities-light to store the user locations. However I need to import a huge dataset of countries & cities to the database.

I use Factory classes for both testing and creating dummy data on the site.

How can I create a factory that would automatically populate these fields during the tests?

When not testing, the factory works properly by Country.objects.all(). But when testing, the database is empty and can not find any countries: IndexError: Cannot choose from an empty sequence.

What should be the right approach for such cases? If you have a better solution to the use of LazyAttributes below, let me know the better approach.

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()
    )

Back to Top