Skip to main content

A model instances generator for Django

Project description

https://badge.fury.io/py/django-fakery.svg https://travis-ci.org/fcurella/django-fakery.svg?branch=master https://coveralls.io/repos/fcurella/django-fakery/badge.svg?branch=master&service=github

An easy-to-use implementation of Creation Methods (aka Object Factory) for Django, backed by Faker.

django_fakery will try to guess the field’s value based on the field’s name and type.

Installation

Install with:

$ pip install django-fakery

QuickStart

from django_fakery import factory

factory.m('app.Model')(field='value')

Alternatively, you can use a more explicit API:

from django_fakery import factory

factory.make(
    'app.Model',
    fields={
        'field': 'value',
    }
)

We will use the short API throught the documentation.

The value of a field can be any python object, a callable, or a lambda:

from django_fakery import factory
from django.utils import timezone

factory.m('app.Model')(created=timezone.now)

When using a lambda, it will receive two arguments: n is the iteration number, and f is an instance of faker:

user = factory.m('auth.User')(
    username=lambda n, f: 'user_{}'.format(n),
)

django-fakery includes some pre-built lambdas for common needs. See shortcuts for more info.

You can create multiple objects by using the quantity parameter:

from django_fakery import factory

factory.m('app.Model', quantity=4)

For convenience, when the value of a field is a string, it will be interpolated with the iteration number:

user = factory.m('auth.User', quantity=4)(
    username='user_{}',
)

Foreign keys

Non-nullable ForeignKey s create related objects automatically.

If you want to explicitly create a related object, you can pass a factory like any other value:

pizza = factory.m('food.Pizza')(
    chef=factory.m('auth.User)(username='Gusteau'),
)

If you’d rather not create related objects and reuse the same value for a foreign key, you can use the special value django_fakery.rels.SELECT:

from django_fakery import factory, rels


pizza = factory.m('food.Pizza', quantity=5)(
    chef=rels.SELECT,
)

django-fakery will always use the first instance of the related model, creating one if necessary.

ManyToManies

Because ManyToManyField s are implicitly nullable (ie: they’re always allowed to have their .count() equal to 0), related objects on those fields are not automatically created for you.

If you want to explicitly create a related objects, you can pass a list as the field’s value:

pizza = factory.m('food.Pizza')(
    toppings=[
        factory.m('food.Topping')(name='Anchovies')
    ],
)

You can also pass a factory, to create multiple objects:

pizza = factory.m('food.Pizza')(
    toppings=factory.m('food.Topping', quantity=5),
)

Shortcuts

django-fakery includes some shortcut functions to generate commonly needed values.

future_datetime(end='+30d')

Returns a datetime object in the future (that is, 1 second from now) up to the specified end. end can be a string, anotther datetime, or a timedelta. If it’s a string, it must start with +, followed by and integer and a unit, Eg: '+30d'. Defaults to '+30d'

Valid units are:

  • 'years', 'y'

  • 'weeks', 'w'

  • 'days', 'd'

  • 'hours', 'hours'

  • 'minutes', 'm'

  • 'seconds', 's'

Example:

from django_fakery import factory, shortcuts
factory.m('app.Model')(field=shortcuts.future_datetime('+1w'))

future_date(end='+30d')

Returns a date object in the future (that is, 1 day from now) up to the specified end. end can be a string, another date, or a timedelta. If it’s a string, it must start with +, followed by and integer and a unit, Eg: '+30d'. Defaults to '+30d'

past_datetime(start='-30d')

Returns a datetime object in the past between 1 second ago and the specified start. start can be a string, another datetime, or a timedelta. If it’s a string, it must start with -, followed by and integer and a unit, Eg: '-30d'. Defaults to '-30d'

past_date(start='-30d')

Returns a date object in the past between 1 day ago and the specified start. start can be a string, another date, or a timedelta. If it’s a string, it must start with -, followed by and integer and a unit, Eg: '-30d'. Defaults to '-30d'

Lazies

You can refer to the created instance’s own attributes or method by using Lazy objects.

For example, if you’d like to create user with email as username, and have them always match, you could do:

from django_fakery import factory, Lazy

factory.m('auth.User')(
    username=Lazy('email'),
)

If you want to assign a value returned by a method on the instance, you can pass the method’s arguments to the Lazy object:

from django_fakery import factory, Lazy

factory.m('myapp.Model')(
    myfield=Lazy('model_method', 'argument', keyword='keyword value'),
)

Pre-save and Post-save hooks

You can define functions to be called right before the instance is saved or right after:

from django_fakery import factory

factory.m(
    'auth.User',
    pre_save=[
        lambda u: u.set_password('password')
    ],
)(username='username')

Since settings a user’s password is such a common case, we special-cased that scenario, so you can just pass it as a field:

from django_fakery import factory

factory.m('auth.User')(
    username='username',
    password='password',
)

Get or Make

You can check for existance of a model instance and create it if necessary by using the g_m (short for get_or_make) method:

myinstance, created = factory.g_m(
    'myapp.Model',
    lookup={
        'myfield': 'myvalue',
    }
)(myotherfield='somevalue')

If you’re looking for a more explicit API, you can use the .get_or_make() method:

myinstance, created = factory.get_or_make(
    'myapp.Model',
    lookup={
        'myfield': 'myvalue',
    },
    fields={
        'myotherfield': 'somevalue',
    },
)

Get or Update

You can check for existence of a model instance and update it by using the g_u (short for get_or_update) method:

myinstance, created = factory.g_u(
    'myapp.Model',
    lookup={
        'myfield': 'myvalue',
    }
)(myotherfield='somevalue')

If you’re looking for a more explicit API, you can use the .get_or_update() method:

myinstance, created = factory.get_or_update(
    'myapp.Model',
    lookup={
        'myfield': 'myvalue',
    },
    fields={
        'myotherfield': 'somevalue',
    },
)

Non persistent instances

You can build instances that are not saved to the database by using the .b() method, just like you’d use .m():

from django_fakery import factory

factory.b('app.Model')(
    field='value',
)

Note that since the instance is not saved to the database, .build() does not support ManyToManies or post-save hooks.

If you’re looking for a more explicit API, you can use the .build() method:

from django_fakery import factory

factory.build(
    'app.Model',
    fields={
        'field': 'value',
    }
)

Blueprints

Use a blueprint:

from django_fakery import factory

user = factory.blueprint('auth.User')

user.make(quantity=10)

Blueprints can refer other blueprints:

pizza = factory.blueprint('food.Pizza').fields(
        chef=user,
    )
)

You can also override the field values you previously specified:

pizza = factory.blueprint('food.Pizza').fields(
        chef=user,
        thickness=1
    )
)

pizza.m(quantity=10)(thickness=2)

Or, if you’d rather use the explicit api:

pizza = factory.blueprint('food.Pizza').fields(
        chef=user,
        thickness=1
    )
)

thicker_pizza = pizza.fields(thickness=2)
thicker_pizza.make(quantity=10)

Seeding the faker

from django_fakery import factory

factory.m('auth.User', seed=1234, quantity=4)(
    username='regularuser_{}'
)

Credits

The API is heavily inspired by model_mommy.

License

This software is released under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-fakery-2.0.2.tar.gz (13.5 kB view details)

Uploaded Source

Built Distribution

django_fakery-2.0.2-py2.py3-none-any.whl (14.1 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file django-fakery-2.0.2.tar.gz.

File metadata

  • Download URL: django-fakery-2.0.2.tar.gz
  • Upload date:
  • Size: 13.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.24.0 CPython/3.6.4

File hashes

Hashes for django-fakery-2.0.2.tar.gz
Algorithm Hash digest
SHA256 a4657ef102fa61f79f654ae97838146c0dfe3336adebcf00b8382bb1578f2425
MD5 132f2af982329d2c9d33177ce44b9eb4
BLAKE2b-256 daeb667560bf6b99eca6b0d715d37f0908d66441b1a40bb47c281a0412b7661a

See more details on using hashes here.

Provenance

File details

Details for the file django_fakery-2.0.2-py2.py3-none-any.whl.

File metadata

  • Download URL: django_fakery-2.0.2-py2.py3-none-any.whl
  • Upload date:
  • Size: 14.1 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.24.0 CPython/3.6.4

File hashes

Hashes for django_fakery-2.0.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 6acd5ecd0baf73ba7fe3ef7edc0f8bd1843eca08a65a452d6c29932e5128fcbd
MD5 65629cdc797cc6038f375421c8bea19b
BLAKE2b-256 68a1a3561d5dc24ec23a0c9e66200a5e0844560e10f7b49c7fbf4158abdc83fd

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page