save a field as JSON using factoryboy
Asked Answered
Y

2

12

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.

Yingyingkow answered 2/6, 2015 at 13:40 Comment(1)
Hi, without seeing any code it is hard to answer this question. What factory_boy will do is simply build a big **kwargs dict and pass it to your Django Model; I'd advise first making some code example of what you want to happen without factory_boy, and only then building it through factory_boy.Dispersant
D
18

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 = ...
Digitize answered 14/12, 2016 at 23:52 Comment(0)
B
-1

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

Bernhardt answered 20/9, 2016 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.