2π
β
As in comment mentioned the factory boy doesnβt have inner dict factory by itself.
The answer in github worked.
First you should make a function that gets factory class and dict all classes in it:
from functools import partial
from typing import Any, Dict
from factory import Factory
from factory.base import StubObject
def generate_dict_factory(factory: Factory):
def convert_dict_from_stub(stub: StubObject) -> Dict[str, Any]:
stub_dict = stub.__dict__
for key, value in stub_dict.items():
if isinstance(value, StubObject):
stub_dict[key] = convert_dict_from_stub(value)
return stub_dict
def dict_factory(factory, **kwargs):
stub = factory.stub(**kwargs)
stub_dict = convert_dict_from_stub(stub)
return stub_dict
return partial(dict_factory, factory)
then for usage:
# example of usage
UserDictFactory = generate_dict_factory(UserFactory)
and finally if call UserDictFactory()
returns what we need.
1π
I was using the answer from Mahmood, and I realized that it was not working properly for lists (when foos = factory.List(FooFactory)
). In this case we would expect to get back a list, but with the original code we get back a dict where the keys are the list indexes as strings.
I made the following modification to fix it:
def generate_dict_factory(factory: factory.Factory):
def stub_is_list(stub: StubObject) -> bool:
try:
return all(k.isdigit() for k in stub.__dict__.keys())
except AttributeError:
return False
def convert_dict_from_stub(stub: StubObject) -> Dict[str, Any]:
stub_dict = stub.__dict__
for key, value in stub_dict.items():
if isinstance(value, StubObject):
stub_dict[key] = (
[convert_dict_from_stub(v) for v in value.__dict__.values()]
if stub_is_list(value)
else convert_dict_from_stub(value)
)
return stub_dict
def dict_factory(factory, **kwargs):
stub = factory.stub(**kwargs)
stub_dict = convert_dict_from_stub(stub)
return stub_dict
return partial(dict_factory, factory)
π€Sergi
- [Django]-Sphinx Note Block in a list under a code block?
- [Django]-Django forms custom validation on two fields one or the other
- [Django]-How do I initialise my Satchmo website?
- [Django]-Django two-column form
Source:stackexchange.com