summaryrefslogtreecommitdiff
path: root/docs/recipes.rst
diff options
context:
space:
mode:
Diffstat (limited to 'docs/recipes.rst')
-rw-r--r--docs/recipes.rst47
1 files changed, 46 insertions, 1 deletions
diff --git a/docs/recipes.rst b/docs/recipes.rst
index df86bac..fe18f50 100644
--- a/docs/recipes.rst
+++ b/docs/recipes.rst
@@ -88,7 +88,7 @@ When a :class:`UserFactory` is instantiated, factory_boy will call
Example: Django's Profile
-"""""""""""""""""""""""""
+~~~~~~~~~~~~~~~~~~~~~~~~~
Django (<1.5) provided a mechanism to attach a ``Profile`` to a ``User`` instance,
using a :class:`~django.db.models.OneToOneField` from the ``Profile`` to the ``User``.
@@ -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
----------------------
@@ -444,3 +458,34 @@ Forcing the initial value for all projects
>>> Account.objects.create(uid=42, name="Blah")
>>> AccountFactory.create() # Sets up the account number based on the latest uid
<Account uid=43, name=Test>
+
+
+Converting a factory's output to a dict
+---------------------------------------
+
+In order to inject some data to, say, a REST API, it can be useful to fetch the factory's data
+as a dict.
+
+Internally, a factory will:
+
+1. Merge declarations and overrides from all sources (class definition, call parameters, ...)
+2. Resolve them into a dict
+3. Pass that dict as keyword arguments to the model's ``build`` / ``create`` function
+
+
+In order to get a dict, we'll just have to swap the model; the easiest way is to use
+:meth:`factory.build`:
+
+.. code-block:: python
+
+ class UserFactory(factory.django.DjangoModelFactory):
+ class Meta:
+ model = models.User
+
+ first_name = factory.Sequence(lambda n: "Agent %03d" % n)
+ username = factory.Faker('username')
+
+.. code-block:: pycon
+
+ >>> factory.build(dict, FACTORY_CLASS=UserFactory)
+ {'first_name': "Agent 001", 'username': 'john_doe'}