Django Model Factory get or create
Asked Answered
V

2

7

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?

Vierno answered 10/12, 2017 at 7:13 Comment(0)
V
2

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
Vierno answered 10/12, 2017 at 7:39 Comment(1)
Does anyone know how we can turn it off ? I mean we have existing django_get_or_create attribute and then we want to turn it off for some casesWiper
N
12

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',)
Nakasuji answered 17/7, 2019 at 10:28 Comment(1)
note that this will fail if you go and override _create like I did 😄Rabiah
V
2

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
Vierno answered 10/12, 2017 at 7:39 Comment(1)
Does anyone know how we can turn it off ? I mean we have existing django_get_or_create attribute and then we want to turn it off for some casesWiper

© 2022 - 2024 — McMap. All rights reserved.