Skip to content

Commit

Permalink
Add documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Nadège Michel committed Oct 30, 2020
1 parent f469305 commit 077c598
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions docs/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -324,10 +324,11 @@ A trait is toggled by a single boolean value:
Strategies
----------

All factories support two built-in strategies:
All factories support three built-in strategies:

* ``build`` provides a local object
* ``create`` instantiates a local object, and saves it to the database.
* ``create async`` similar to create but can run asynchronous code.

.. note:: For 1.X versions, the ``create`` will actually call ``AssociatedClass.objects.create``,
as for a Django model.
Expand All @@ -351,13 +352,64 @@ Calling a :class:`~factory.Factory` subclass will provide an object through the
.. code-block:: pycon
>>> MyFactory.create()
<MyFactory: X (saved)>
<MyClass: X (saved)>
>>> MyFactory.create_async()
<MyClass: X (saved using async code)>
>>> MyFactory.build()
<MyFactory: X (unsaved)>
<MyClass: X (unsaved)>
>>> MyFactory() # equivalent to MyFactory.create()
<MyClass: X (saved)>
The default strategy can be changed by setting the ``class Meta`` :attr:`~factory.FactoryOptions.strategy` attribute.


Async Factories
---------------

If your project uses asynchronous code to save objects to database, you
can use that in your factories too.

You need to override the async method :meth:`factory.Factory._create_model_async`
to define how your objects are created and saved to the database.

You can then either:

* use :meth:`factory.Factory.create_async`
* inherit from `:class:`~factory.AsyncFactory` instead of `:class:`~factory.Factory`
to make ``create async`` the default strategy and then call the factory.

.. code-block:: python
class MyClass:
...
@classmethod
async def write_in_db(*args, **kwargs):
...
class MyFactory(factory.AsyncFactory):
class Meta:
model = MyClass
@classmethod
async def _create_model_async(cls, model_class, *args, **kwargs):
await model_class.write_in_db(*args, **kwargs)
.. code-block:: pycon
>>> MyFactory.create()
<MyClass: X (saved)>
>>> MyFactory.create_async()
<MyClass: X (saved using async code)>
>>> MyFactory.build()
<MyClass: X (unsaved)>
>>> MyFactory() # equivalent to MyFactory.create_async()
<MyClass: X (saved using async code)>

0 comments on commit 077c598

Please sign in to comment.