Search code examples
djangodjango-modelsfactory-boy

How to reset_sequence to default id field sequence in DjangoModelFactory


With a factory like:

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

The model's id field will by default start at 1. I want the id to start at a higher number, eg 50000.

Using UserFactory.reset_sequence(50000) does not work unless you add this line in the factory

id = factory.Sequence(lambda n: n)

I have a lot of tests that depend on the default id increment behavior so this way is a no go.


Solution

  • The only workaround I could find is by creating a User object starting at 49999

    if not UserFactory.objects.filter(id=49999).exists():
        UserFactory(49999)
    

    Now you can do

    print(UserFactory().id)
    >>> 50000
    

    Now if your model's id is an autofield, you'll likely have to alter the underlying database schema, or resort to the reset_sequence method. How to get Django AutoFields to start at a higher number