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

1

7

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.

Decentralize answered 30/8, 2018 at 14:54 Comment(1)
do you want this only for create_batch? why not to do order = factory.Sequence(lambda n: n * 10) in the factory?Alasteir
R
9

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))
Rumba answered 1/4, 2020 at 15:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.