🏭 An easy-to-use implementation of Creation Methods for Django, backed by Faker.

Overview

Django-fakery

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
from myapp.models import MyModel

factory.m(MyModel)(field='value')

If you're having issues with circular imports, you can also reference a model by using the M utility function:

from django_fakery import factory, M

factory.m(M("myapp.MyModel"))(field="value")

If you really don't want to import things, you could also just reference a model by using the <app_label>.<ModelName> syntax. This is not encouraged, as it will likely break type-hinting:

from django_fakery import factory

factory.m("myapp.MyModel")(field="value")

If you use pytest, you can use the fakery fixture (requires pytest and pytest-django):

import pytest
from myapp.models import MyModel

@pytest.mark.django_db
def test_mymodel(fakery):
    fakery.m(MyModel)(field='value')

If you'd rather, you can use a more wordy API:

from django_fakery import factory
from myapp.models import MyModel

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

We will use the short API thorough the documentation.

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

from django.utils import timezone
from django_fakery import factory
from myapp.models import MyModel

factory.m(MyModel)(created=timezone.now)

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

from django.contrib.auth.models import User

user = factory.m(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
from django.contrib.auth.models import User

factory.m(User, quantity=4)

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

from myapp.models import MyModel

user = factory.m(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:

from django.contrib.auth.models import User
from food.models import Pizza

pizza = factory.m(Pizza)(
    chef=factory.m(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
from food.models import Pizza

pizza = factory.m(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:

from food.models import Pizza, Topping

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

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

from food.models import Pizza, Topping

pizza = factory.m(Pizza)(
    toppings=factory.m(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
from myapp.models import MyModel

factory.m(MyModel)(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
from django.contrib.auth.models import User

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
from myapp.models import MyModel

factory.m(MyModel)(
    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.contrib.auth.models import User
from django_fakery import factory

factory.m(
    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.contrib.auth.models import User
from django_fakery import factory

factory.m(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:

from myapp.models import MyModel

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

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

from myapp.models import MyModel

myinstance, created = factory.get_or_make(
    MyModel,
    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:

from myapp.models import MyModel

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

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

from myapp.models import MyModel

myinstance, created = factory.get_or_update(
    MyModel,
    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
from myapp.models import MyModel

factory.b(MyModel)(
    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
from myapp.models import MyModel

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

Blueprints

Use a blueprint:

from django.contrib.auth.models import User
from django_fakery import factory

user = factory.blueprint(User)

user.make(quantity=10)

Blueprints can refer other blueprints:

from food.models import Pizza

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

You can also override the field values you previously specified:

from food.models import Pizza

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

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

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

from food.models import Pizza

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

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

Seeding the faker

from django.contrib.auth.models import User
from django_fakery import factory

factory.m(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.

A clone of https://virgool.io written in django

Virgool clone A clone of virgool blog written in django Installation first rename the .env.sample to .env and fill it. with docker docker-compose up -

Danial Selmipoor 7 Dec 23, 2022
a little task queue for python

a lightweight alternative. huey is: a task queue (2019-04-01: version 2.0 released) written in python (2.7+, 3.4+) clean and simple API redis, sqlite,

Charles Leifer 4.3k Dec 29, 2022
Set the draft security HTTP header Permissions-Policy (previously Feature-Policy) on your Django app.

django-permissions-policy Set the draft security HTTP header Permissions-Policy (previously Feature-Policy) on your Django app. Requirements Python 3.

Adam Johnson 78 Jan 02, 2023
This is a personal django website for forum posts

Django Web Forum This is a personal django website for forum posts It includes login, registration and forum posts with date time. Tech / Framework us

5 May 12, 2022
No effort, no worry, maximum performance.

Django Cachalot Caches your Django ORM queries and automatically invalidates them. Documentation: http://django-cachalot.readthedocs.io Table of Conte

NoriPyt 980 Jan 06, 2023
Login System Django

Login-System-Django Login System Using Django Tech Used Django Python Html Run Locally Clone project git clone https://link-to-project Get project for

Nandini Chhajed 6 Dec 12, 2021
Repo for All the Assignments I have to submit for Internship Application !😅

Challenges Repository for All the Assignments I have to submit for Internship Application ! 😅 As You know, When ever We apply for an Internship, They

keshav Sharma 1 Sep 08, 2022
A prettier way to see Django requests while developing

A prettier way to see Django requests while developing

Adam Hill 35 Dec 02, 2022
Modular search for Django

Haystack author: Daniel Lindsley date: 2013/07/28 Haystack provides modular search for Django. It features a unified, familiar API that allows you to

Daniel Lindsley 4 Dec 23, 2022
Packs a bunch of smaller CSS files together from 1 folder.

Packs a bunch of smaller CSS files together from 1 folder.

1 Dec 09, 2021
Simple API written in Python using FastAPI to store and retrieve Books and Authors.

Simple API made with Python FastAPI WIP: Deploy in AWS with Terraform Simple API written in Python using FastAPI to store and retrieve Books and Autho

Caio Delgado 9 Oct 26, 2022
A Django app to accept payments from various payment processors via Pluggable backends.

Django-Merchant Django-Merchant is a django application that enables you to use multiple payment processors from a single API. Gateways Following gate

Agiliq 997 Dec 24, 2022
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
File and Image Management Application for django

Django Filer django Filer is a file management application for django that makes handling of files and images a breeze. Contributing This is a an open

django CMS Association 1.6k Dec 28, 2022
Improved Django model inheritance with automatic downcasting

Polymorphic Models for Django Django-polymorphic simplifies using inherited models in Django projects. When a query is made at the base model, the inh

1.4k Jan 03, 2023
A Django Online Library Management Project.

Why am I doing this? I started learning 📖 Django few months back, and this is a practice project from MDN Web Docs that touches the aspects of Django

1 Nov 13, 2021
Resolve form field arguments dynamically when a form is instantiated

django-forms-dynamic Resolve form field arguments dynamically when a form is instantiated, not when it's declared. Tested against Django 2.2, 3.2 and

DabApps 108 Jan 03, 2023
An app that allows you to add recipes from the dashboard made using DJango, JQuery, JScript and HTMl.

An app that allows you to add recipes from the dashboard. Then visitors filter based on different categories also each ingredient has a unique page with their related recipes.

Pablo Sagredo 1 Jan 31, 2022
Source code for Django for Beginners 3.2

The official source code for https://djangoforbeginners.com/. Available as an ebook or in Paperback. If you have the 3.1 version, please refer to this

William Vincent 10 Jan 03, 2023
ProjectManagementWebsite - Project management website for CMSC495 built using the Django stack

ProjectManagementWebsite A minimal project management website for CMSC495 built

Justin 1 May 23, 2022