user2077935
user2077935

Reputation: 388

Django Model Factory get or create

I have a Django Model defined like below:

    class CustomModel(models.Model):
        column = models.CharField(max_length=50, unique=True)

Define a Factory for the model

from factory_boy import DjangoModelFactory
class CustomModelFactory(DjangoModelFactory):
    
    column = 'V1'

FACTORY_FOR = CustomModelFactory()

How do i make sure that factory implements get_or_create instead of a create everytime?

Does anyone know how can this be done?

Upvotes: 7

Views: 12576

Answers (2)

user2077935
user2077935

Reputation: 388

The way to implement this is by structuring your Factory class as follow:

class CustomModelFactory(DjangoModelFactory):
    class Meta:
        django_get_or_create = ('column',)
    column = 'V1'

FACTORY_FOR = CustomModel

Upvotes: 2

Lingster
Lingster

Reputation: 1087

As per the factory docs: https://factoryboy.readthedocs.io/en/latest/orms.html#factory.django.DjangoOptions.django_get_or_create

They way to use get_or_create instead of create is to add "FACTORY_DJANGO_GET_OR_CREATE" with the list of fields which will be used for the get:

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'myapp.User'  # Equivalent to ``model = myapp.models.User``
        django_get_or_create = ('username',)

so in your example this would look like this:

    class CustomModelFactory(DjangoModelFactory):
        class Meta:
            model = CustomModel
            django_get_or_create = ('column',)

Upvotes: 13

Related Questions