Django Factory Boy iterate over related parent
<p>I have a project with Clients, Draftschedules, LineItems and Servers.</p>

<ul>
<li><p>Each client has a single DraftSchedule, each Draftschedule has many Lineitems</p></li>
<li><p>Each Client has many Servers</p></li>
<li><p>Each LineItem has a Single Server</p></li>
</ul>

<p><a href="http://i.stack.imgur.com/JPRI1.png" rel="nofollow"><img src="http://i.stack.imgur.com/JPRI1.png" alt="enter image description here"></a></p>

<p>I have some code to generate LineItems for each DraftSchedule with random data. However the resulting LineItems contain Servers not actually owned by the Draftschedule Client</p>

<pre><code>class LineItemFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = LineItem

    line_item_type = factory.Iterator(LineItemType.objects.all())
    draftschedule = factory.Iterator(DraftSchedule.objects.all())

    servers = factory.Iterator(Server.objects.all())  # &lt;----- Problem line

    cost = factory.LazyAttribute(lambda x: faker.pydecimal(2, 2, positive=True))
    detail = factory.LazyAttribute(lambda x: faker.sentence())
    ...
</code></pre>

<p>I'd like to restrict the server choice set to be only those servers owned by the parent client of the Draftschedule the Lineitem is being created for.</p>

<p>So that when I call <code>LineItemFactory()</code> it returns a new LineItem object and I can garantee that the Server on the LineItem is actually owned by the Client associated with the DraftSchedule</p>

<p>I've tried the following:</p>

<pre><code>servers = factory.Iterator(lambda x: x.draftschedule.client.servers.all())
</code></pre>

<p>where <code>client.servers</code> is the related name, but the function isn't iterable so I'm a bit stuck</p>

<p>Is this possible or should I approach the problem from a different angle?</p>

<p>You could try using a <a href="http://factoryboy.readthedocs.io/en/latest/reference.html#id6" rel="nofollow">lazy_attribute_sequence</a> :</p>

<pre><code>@factory.lazy_attribute_sequence
def servers(obj, seq):
    all_servers = obj.draftschedule.client.servers.all()
    nb_servers = all_servers.count()
    return all_servers[seq % nb_servers]
</code></pre>

python django fixtures factory-boy