Initializing foreign key value via parent factory argument

44 views
Skip to first unread message

Rich Rauenzahn

unread,
Apr 5, 2016, 7:26:07 PM4/5/16
to Factory Boy

Let's say I have these Django models:

class State(Model):
    name = CharField(max_length=2)

class Address(Model):
    state = ForeignKey(State) 
    ...

Would it be possible to create an Address factory where I could pass two letter strings to AddressFactory() for the state and the ForeignKey is automatically created?

I tried overriding __init__ for AddressFactory and that didn't work -- it wasn't called.

class AddressFactory(DjangoModelFactory):

     def __init__(self, *args, **kwargs)
         state = kwargs.get('state')
         if isinstance(state, basestring):
            kwargs['state'] = StateFactory(name=state)
         super(AddressFactory, self).__init__(*args, **kwargs)

Besides it not working, I also see this has a problem with is StateFactory doesn't inherit the strategy, but I think you can see what I'm trying to accomplish?


Rich Rauenzahn

unread,
Apr 5, 2016, 7:35:08 PM4/5/16
to Factory Boy
 Reading more of the code I see I need to override the classmethod __call__ .... but I'm unsure how to propagate the strategy.

Raphaël Barrois

unread,
Apr 6, 2016, 5:50:23 AM4/6/16
to Rich Rauenzahn, Factory Boy
Hi,

With the new (unreleased) parameters section, this would be possible with the following code:

class AddressFactory(factory.django.DjangoModelFactory):

class Params
state_code = ''

state = factory.SubFactory(StateFactory, code=factory.SelfAttribute('..state_code'))

And then, simply call:

AddressFactory(state_code='CA')

This translates to:

Address.objects.create(
state=State.objects.create(code='CA'),
)


Does that solve your issue?

Rich Rauenzahn

unread,
Apr 6, 2016, 4:04:15 PM4/6/16
to Raphaël Barrois, Rich Rauenzahn, Factory Boy

Yes, I think it would! Thank you!

Rich
Reply all
Reply to author
Forward
0 new messages