Anshul Sharma
Anshul Sharma

Reputation: 347

Fake JSONField using Factory Boy

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?

Upvotes: 4

Views: 3341

Answers (1)

Hammadi Ilyes
Hammadi Ilyes

Reputation: 469

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'

Upvotes: 3

Related Questions