I have a Django model like this:
class NicePerson(models.Model):
last_name = models.CharField(max_length=100)
def save(self, make_irish=False, *args, **kwargs):
"""if make_irish is True, prepend last_name with O'"
if make_irish:
self.last_name = "O'" + self.last_name
super(MyModel, self).save(*args, **kwargs)
And I have a FactoryBoy class to build NicePerson instances
class NicePersonFactory(factory.django.DjangoModelFactory):
class Meta:
model = NicePerson
I know I can use these together like so:
nice_person = NicePersonFactory(last_name='Shea')
But how can I pass the "make_irish" parameter to my save() method?
factory_boy uses the default manager for creation, i.e it calls NicePerson.objects.create() or NicePerson.objects.get_or_create().
For your example, you could override those managers (in your Model definition):
class NicePersonManager(models.Manager):
def create(self, *args, **kwargs):
if kwargs.pop('make_irish', False):
kwargs.update(...)
return super().create(*args, **kwargs)
Another option would be to override your factory's _create and _get_or_create methods. For instance:
class NicePersonFactory(factory.django.DjangoModelFactory):
@classmethod
def _create(cls, model_class, *args, **kwargs):
make_irish = kwargs.pop('make_irish', False)
instance = model_class(**kwargs)
instance.save(make_irish=make_irish)
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With