create consistant department name and code

249 Views Asked by At

I have a department model in django:

from django.db import models

class Departement(models.Model):
    name = models.CharField(max_length=128, db_index=True)
    code = models.CharField(max_length=3, db_index=True)

I'd like to create a fixture with factory_boy with a consistent department name and code.

Faker has a department provider which returns a tuple with the code and the department (ex for french: https://faker.readthedocs.io/en/master/locales/fr_FR.html#faker.providers.address.fr_FR.Provider.department)

I have created a DepartmentFixture class but fail to understand how to use an instance of faker to call the faker.derpartments() method then populate the code/name fields accordingly.

2

There are 2 best solutions below

3
weAreStarsDust On

I gues factory.Faker() is what you are searching for

import factory
from myapp.models import Departement

class DepartmentFixture(factory.django.DjangoModelFactory):
    class Meta:
        model = Departement

    class Params:
        department_tuple = factory.Faker('department')
    
    name = factory.LazyAttribute(lambda obj: obj.department_tuple[1])
    code = factory.LazyAttribute(lambda obj: obj.department_tuple[0])
0
Rémi Desgrange On

Following @weAreStarsDust I finally make this work:

import factory
from myapp.models import Departement

class DepartmentFixture(factory.django.DjangoModelFactory):
    class Meta:
        model = Departement

    class Params:
        department = factory.Faker('department')

    name = factory.LazyAttribute(lambda d: d.department_tuple[1])
    code = factory.LazyAttribute(lambda d: d.department_tuple[0])