Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set length for python Faker fields

I am trying to set up UserFactory using DjangoModelFactory from factory_boy and Faker. Here is my code.

fake = Faker('uk_UA')

class UserFactory(DjangoModelFactory):
    class Meta:
        model = User

    username = fake.user_name
    first_name = fake.first_name_male
    last_name = fake.last_name_male

    email = fake.safe_email

But when I try to use it I got error:

    DataError                  Traceback (most recent call last)
/Users/mero/.virtualenvs/fine-hut/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params)
     63             else:
---> 64                 return self.cursor.execute(sql, params)
     65

DataError: value too long for type character varying(30)

I assume that problem is in too long fields generated by Faker. But I didn't find any way to restrict it's length in python, though found few answers for Ruby Faker.

Is there way to do this in python Faker? Or maybe there is some other way to use Faker for generate locale-specific fields?

like image 875
Myroslav Hryshyn Avatar asked Aug 06 '17 06:08

Myroslav Hryshyn


2 Answers

Two possibilities that have worked for me:

Option 1: LazyAttribute If you evaluate this outside of factory_boy's Faker implementation, you can pass that into the LazyAttribute factory method and take the length of that:

from faker import Factory as FakerFactory
faker = FakerFactory.create()

class MyFactory(DjangoModelFactory):
    class Meta:
        model = MyModel
    some_attr = factory.LazyAttribute(lambda n: faker.sentence()[:10])

Option 2: Fuzzy instead of Faker: If you don't care about losing actual attributes of the provider, and would be okay with just a random string of text of the set length, you can do:

import factory.fuzzy   # necessary; can't just do import factory

class MyFactory(DjangoModelFactory):
    class Meta:
        model = MyModel
    some_attr = factory.fuzzy.FuzzyText(length=10)
like image 166
Robert Townley Avatar answered Oct 17 '22 00:10

Robert Townley


Have found workaround:

class UserFactory(DjangoModelFactory):
    class Meta:
        model = User

    username = factory.Faker('user_name', locale='uk_UA')
    first_name = factory.Faker('first_name', locale='uk_UA')
    last_name = factory.Faker('last_name', locale='uk_UA')

    email = factory.Faker('safe_email', locale='uk_UA')

It works for me, but still interesting if there is an option to set length of field in Faker.

like image 37
Myroslav Hryshyn Avatar answered Oct 17 '22 01:10

Myroslav Hryshyn