[Solved]-How to create factory-boy factories for Django models with the same foreign key

6👍

You can use the Params option (http://factoryboy.readthedocs.io/en/latest/reference.html#parameters):

class RecordingFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Recording

    class Params:
        language = factory.SubFactory(Language)

    subtitles = factory.SubFactory(SubtitlesFactory, 
        language=factory.SelfAttribute('language'))
    audio = factory.SubFactory(AudioFactory, 
        language=factory.SelfAttribute('language'))
👤Xelnor

1👍

Possible solution is to generate the shared foreign key model, assign it to each subfactory, and then remove it before creating the model.

class RecordingFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Recording

    subtitles = factory.SubFactory(
        SubtitlesFactory,
        language=factory.SelfAttribute('.._language')
    )
    audio = factory.SubFactory(
        AudioFactory,
        language=factory.SelfAttribute('.._language')
    )

    _language = factory.SubFactory(Language)

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        kwargs.pop("_language")
        return super()._create(model_class, *args, **kwargs)

Leave a comment