使用factoryboy将字段另存为JSON [英] save a field as JSON using factoryboy

查看:73
本文介绍了使用factoryboy将字段另存为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建其中一个字段为JSONField的模型的实例.通过factoryboy创建模型实例时,我想在测试数据库中将字段另存为JSONField.只需将字段作为JSON传递,就将其存储为Unicode数据类型.我被困住了.

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.

推荐答案

您可以使用

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

例如如果您希望将dict数据序列化为JSON字符串,则可以执行以下操作:

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

这篇关于使用factoryboy将字段另存为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆