save a field as JSON using factoryboy

一笑奈何 提交于 2019-12-22 06:47:33

问题


I am trying to create an instance of the model in which one of the field is JSONField. When creating the instance of model via factoryboy, I want to save the field as JSONField in the test database. On simply passing the field as JSON,it gets stored in Unicode data type. I am stuck on this.


回答1:


You can create dict data using a factory.Dict. You can then control the final form of the data using the dict_factory attribute.

e.g. if you want to have dict data that is serialised to a JSON string, you can do something like this:

import json
import factory


class JSONFactory(factory.DictFactory):
    """
    Use with factory.Dict to make JSON strings.
    """
    @classmethod
    def _generate(cls, create, attrs):
        obj = super()._generate(create, attrs)
        return json.dumps(obj)


class BadgerFactory(factory.Factory):

    form_data = factory.Dict({
        'badger': ['stoat'],
    }, dict_factory=JSONFactory)

    class Meta:
        model = ...



回答2:


Have you tried passing the value as a dictionary? It must be then converted to JSON.



来源:https://stackoverflow.com/questions/30597804/save-a-field-as-json-using-factoryboy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!