When using factory_boy in Django, how can I achieve this?
models.py
class TestModel(models.Model):
name = CharField()
order = IntegerField()
recipes.py
class TestModelFactory(factory.django.DjangoModelFactory):
class Meta:
model = TestModel
name = factory.LazyAttribute(lambda o: faker.word().title())
order = 0
tests.py
recipes.TestModelFactory.create_batch(4, order=+10)
or
recipes.TestModelFactory.create_batch(4, order=seq(10))
or something along those lines, to achieve this result:
TestModel.objects.all().values_list('order', flat=True)
[10, 20, 30, 40]
UPDATE
Ty @trinchet for the idea. So I guess one solution would be:
class TestModelFactory(factory.django.DjangoModelFactory):
class Meta:
model = TestModel
name = factory.LazyAttribute(lambda o: faker.word().title())
order = factory.Sequence(lambda n: n * 10)
But that would always set sequences on all my objects, without me being able to set values that I want.
A workaround that is:
class TestModelFactory(factory.django.DjangoModelFactory):
class Meta:
model = TestModel
name = factory.LazyAttribute(lambda o: faker.word().title())
order = 0
And then in tests:
recipes.MenuItemFactory.reset_sequence(1)
recipes.MenuItemFactory.create_batch(
4,
parent=self.section_menu,
order=factory.Sequence(lambda n: n * 10)
)
Which will give me the result that I want. But this resets all the sequences. I want it to be able to dynamically set the sequence just for order.
create_batch
? why not to doorder = factory.Sequence(lambda n: n * 10)
in the factory? – Alasteir