Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 382
askvictor Avatar asked Mar 03 '26 10:03

askvictor


2 Answers

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

like image 94
bryanph Avatar answered Mar 05 '26 07:03

bryanph


You can customize the _create method.

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

like image 43
Tomasz Zieliński Avatar answered Mar 05 '26 06:03

Tomasz Zieliński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!