How to make factory use `objects.create_user` instead of `objects.create` when creating model

Is there a way to make instantiating instances from factories use Model.objects.create_user instead of Model.objects.create? It seems that user_factory.create uses the latter, which makes the below code succeed even though username is a required field and not passed.

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

@pytest.fixture
def new_user2(user_factory):
    return user_factory.create(first_name='abc')

You can override _create method of DjangoModelFactory

class UserFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = User

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        manager = cls._get_manager(model_class)
        return manager.create_user(*args, **kwargs)

You can find the documentation about this method here : https://factoryboy.readthedocs.io/en/stable/reference.html#factory.Factory._create

Back to Top