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.
factory_boy is a fixtures replacement based on thoughtbot's factory_bot. As a fixtures replacement tool, it aims to replace static, hard to maintain fixtures with easy-to-use factories for complex objects.
DjangoModelFactory is a basic interface from factory_boy that gives "ORM powers" to your factories. It's main feature here is that it provides you with a common "create" and "build" strategies that you can use to generate objects in your tests.
Just in case someone find it helpful.
I've found this post trying to implement negative sort order sequence. And only in the create_batch call. So my use-case was
MyModelFactory.create_batch(
9,
sort_order=factory.Sequence(lambda n: 10-n))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With