I have two Django models (Customer
and CustomerAddress
) that both contain ForeignKey
s to each other. I am using factory-boy to manage creation of these models, and cannot save a child factory instance onto the parent factory (using relationships defined using the RelatedFactory
class).
My two models:
class ExampleCustomerAddress(models.Model):
# Every customer mailing address is assigned to a single Customer,
# though Customers may have multiple addresses.
customer = models.ForeignKey('ExampleCustomer', on_delete=models.CASCADE)
class ExampleCustomer(models.Model):
# Each customer has a single (optional) default billing address:
default_billto = models.ForeignKey(
'ExampleCustomerAddress',
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name='+')
I have two factories, one for each model:
class ExampleCustomerAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = ExampleCustomerAddress
customer = factory.SubFactory(
'ExampleCustomerFactory',
default_billto=None) # Set to None to prevent recursive address creation.
class ExampleCustomerFactory(factory.django.DjangoModelFactory):
class Meta:
model = ExampleCustomer
default_billto = factory.RelatedFactory(ExampleCustomerAddressFactory,
'customer')
When creating a ExampleCustomerFactory
, default_billto
is None, even though a ExampleCustomerAddress
has been created:
In [14]: ec = ExampleCustomerFactory.build()
In [15]: ec.default_billto is None
Out[15]: True
(When using create()
, a new ExampleCustomerAddress
exists in the database. I am using build()
here to simplify the example).
Creating an ExampleCustomerAddress
works as expected, with the Customer
being automatically created:
In [22]: eca = ExampleCustomerAddressFactory.build()
In [23]: eca.customer
Out[23]: <ExampleCustomer: ExampleCustomer object>
In [24]: eca.customer.default_billto is None
Out[24]: True <-- I was expecting this to be set to an `ExampleCustomerAddress!`.
I feel like I am going crazy here, missing something very simple. I get the impression I am encountering this error because of how both models contain ForeignKeys
to each other.
CustomerFactory
. It never occurred to me to place it onto theCustomerAddressFactory
. One quick edit to your answer: the@factory.post_declaration
decorator should be@factory.post_generation
. – Sutlej