Fake JSONField using Factory Boy

3.1k views Asked by At

I have a field in my model with JSONField Type(MYSQL Implementation). I want to fake the data for this field using FactoryBoy Faker.

How can I achieve this?

1

There are 1 answers

0
Hammadi Ilyes On

You can resolve this issue by creating a function that returns a dict instead of a single string, data is a JSONField in the User model. You can also use this same code with PostgreSql JSONField it also returns a dict in the model field.

import factory


def sequence(number):
   """
   :param number:
   :return: a dict that contains random data
   """
   return {
       'email': 'example{0}@foo.com'.format(number),
       'username': 'username{0}'.format(number),
   }


class UserFactory(factory.django.DjangoModelFactory):
    data = factory.Sequence(sequence)

    class Meta:
        model = 'users.User'