askvictor
askvictor

Reputation: 3819

Factory boy in django for non-database fields

I have a django model which, on save, triggers the creation of an account on an external service (not related to django in any way). For testing, though, I'd like to suppress this account creation. I can override the manager's save() method and pop the kwarg from there, or I could add a non-database-field property to the model as per Non-database field in Django model and check for that in my save method.

However, when I try to use factoryboy to create my objects, it seems to check for real fields in the model, which crashes due to the property not being a field.

class MyModel(models.Model):
    name = models.CharField()
    create_external_account = True
    def save(self, *args, **kwargs):
        if create_external_account:
            ...

class MyModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = MyModel
    name = factory.Sequence(lambda n: 'name%d' % n)
    create_external_account = False

Any thoughts on how I can pass an extra parameter such as this through factoryboy?

Upvotes: 3

Views: 2722

Answers (3)

bryanph
bryanph

Reputation: 1012

You can use exclude, which has been added in 2.4.0 See http://factoryboy.readthedocs.org/en/latest/reference.html#factory.FactoryOptions.exclude

Upvotes: 3

Xelnor
Xelnor

Reputation: 3589

factory_boy's create() calls your model's MyModel.objects.create(**kwargs) method.

When you write MyModelFactory(), this calls:

obj = MyModel(name="name01", create_external_account=False)
obj.save()
return obj

Here, you should override your model's __init__ method to handle your custom field:

class MyModel(django.db.models.Model):
    def __init__(self, *args, **kwargs):
        self.create_external_account = kwargs.pop('create_external_account', False)
        return super(MyModel, self).__init__(*args, **kwargs)

Upvotes: 1

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16356

You can customize the _create method.

You can also disable signals if the external account is created in a signal handler.

Upvotes: 1

Related Questions