[Django]-How to convert factory boy instance as json

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

Leave a comment