Saša Kalaba
Saša Kalaba

Reputation: 4411

How to setup a sequence for an attribute while using create_batch in factory-boy?

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.

Upvotes: 7

Views: 5663

Answers (1)

Fallen Flint
Fallen Flint

Reputation: 319

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

Upvotes: 9

Related Questions