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 Nov 27, 2020
1 parent cbba77a commit 780909f
Showing 1 changed file with 52 additions and 3 deletions.
55 changes: 52 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,61 @@ 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
---------------

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.

Then, you can then either:

* use :meth:`factory.Factory.create_async`
* have you factory inherit from :class:`factory.AsyncFactory` instead of :class:`~factory.Factory`
to make :attr:`enums.ASYNC_CREATE_STRATEGY` 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 780909f

Please sign in to comment.