Search code examples
pythondjangodjango-rest-frameworkfactory-boy

How to convert factory boy instance as json


I have a model that relates to some others and I want to make an instance of model factory with factory boy package and send it as json to rest API in django rest framework.

UserFactory:

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User
    first_name = factory.Faker('name')
    username = factory.Faker('word')
    language = factory.SubFactory(LanguageFactory)

LanguageFactory:

class LanguageFactory(factory.django.DjangoModelFactory):
class Meta:
    model = Language

name = factory.Faker('language_name')

When I use:

factory.build(dict, FACTORY_CLASS=UserFactory)

it returns:

{'first_name': "Agent 001", 'username': 'john_doe', 'language': <Language: Catalan>}

where language is another model factory but I need it as json to post or patch test.

How would I get something like this?

{'first_name': "Agent 001", 'username': 'john_doe', 'language': [{'name': 'English'}, {'name': 'French'}]}

Solution

  • 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.