How to create factory-boy factories for Django models with the same foreign key
<p>I keep running into issues with my factories when two or more models have a common foreign key, and each one creates their own object when they should have the same.</p>

<p>To illustrate the problem, here is a simplified model structure:</p>

<pre><code>class Language (models.Model):
    code = models.CharField(max_length=3, unique=True)


class Audio(models.Model):
    language = models.ForeignKey(Language)
    soundfile = models.FileField()


class Subtitles(models.Model):
    language = models.ForeignKey(Language)
    text = models.TextField()


class Recording(models.Model):
    audio = models.ForeignKey(Audio)
    subtitles = models.ForeignKey(Subtitles)
</code></pre>

<p>So a <code>Recording</code> has <code>Audio</code> and <code>Subtitles</code>, and both of those have a <code>Language</code> which is unique for each language code.</p>

<p>Here are the factories for this structure.</p>

<pre><code>class LanguageFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Language


class AudioFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Audio

    language = factory.SubFactory(LanguageFactory, code='en1')


class SubtitlesFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Subtitles

    language = factory.SubFactory(LanguageFactory, code='en1')


class RecordingFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Recording

    audio = factory.SubFactory(AudioFactory)
    subtitles = factory.SubFactory(SubtitlesFactory)
</code></pre>

<p>It's a very common case that the audio and subtitles have the same language, since generally it's just a transcript. So I want a default RecordingFactory to have audio and subtitles with a language of 'en1' as code, as reflected in the factories above.</p>

<p>But since each factory tries to create its own instance of language, instantiating a RecordingFactory with <code>recording = RecordingFactory()</code> (which I do a lot) raises an exception:</p>

<pre><code>IntegrityError: UNIQUE constraint failed: recordings_language.code
</code></pre>

<p>To solve it, I can do something like this:</p>

<pre><code>language = LanguageFactory(code='en1')
recording = RecordingFactory(subtitles__language=language, audio__language=language)
</code></pre>

<p>But that's verbose. In my real project I have even more connections so sometimes I need to specify the language in three or four places, sometimes four levels deep. Instead, I would like to be able to specify a default that is either created or used if it already exists.</p>

<p>What is the correct way around this, if one exists?</p>