From 5836329889ac45034978c69b6a6f7de4b0b5b75d Mon Sep 17 00:00:00 2001 From: Samuel Paccoud Date: Sun, 3 Apr 2016 09:42:40 +0200 Subject: Add documentation and test for subfactory using "factory_parent" attribute Add documentation on how to use a LazyAttribute in a SubFactory and poke the "factory_parent" attribute to indirectly derive the value of a field on the child factory from a field on the parent factory. This commit adds an example to recipes that explains how it can be done. It also adds a test to make sure that this feature continues to work as is now described in the documentation. --- docs/recipes.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'docs') diff --git a/docs/recipes.rst b/docs/recipes.rst index a3df7be..fe18f50 100644 --- a/docs/recipes.rst +++ b/docs/recipes.rst @@ -327,7 +327,21 @@ Here, we want: country = factory.SubFactory(CountryFactory) owner = factory.SubFactory(UserFactory, country=factory.SelfAttribute('..country')) +If the value of a field on the child factory is indirectly derived from a field on the parent factory, you will need to use LazyAttribute and poke the "factory_parent" attribute. +This time, we want the company owner to live in a country neighboring the country of the company: + +.. code-block:: python + + class CompanyFactory(factory.django.DjangoModelFactory): + class Meta: + model = models.Company + + name = "ACME, Inc." + country = factory.SubFactory(CountryFactory) + owner = factory.SubFactory(UserFactory, + country=factory.LazyAttribute(lambda o: get_random_neighbor(o.factory_parent.country))) + Custom manager methods ---------------------- -- cgit v1.2.3