{"id":13416068,"url":"https://github.com/fcurella/django-fakery","last_synced_at":"2025-04-07T07:08:20.267Z","repository":{"id":45885204,"uuid":"43170767","full_name":"fcurella/django-fakery","owner":"fcurella","description":"🏭  An easy-to-use implementation of Creation Methods for Django, backed by Faker.","archived":false,"fork":false,"pushed_at":"2024-07-07T07:47:13.000Z","size":444,"stargazers_count":114,"open_issues_count":3,"forks_count":6,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-10-14T21:51:37.630Z","etag":null,"topics":["creation-methods","django","testing"],"latest_commit_sha":null,"homepage":"http://django-fakery.readthedocs.org/en/stable/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fcurella.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-09-25T19:16:35.000Z","updated_at":"2024-09-20T17:33:57.000Z","dependencies_parsed_at":"2024-01-11T19:17:12.433Z","dependency_job_id":"ba45795d-380c-4a69-9a36-616166cfa4af","html_url":"https://github.com/fcurella/django-fakery","commit_stats":{"total_commits":278,"total_committers":5,"mean_commits":55.6,"dds":"0.046762589928057596","last_synced_commit":"5e3d33582b475b1c3b5b595bb7caebffd4de041a"},"previous_names":[],"tags_count":73,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fcurella%2Fdjango-fakery","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fcurella%2Fdjango-fakery/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fcurella%2Fdjango-fakery/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fcurella%2Fdjango-fakery/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fcurella","download_url":"https://codeload.github.com/fcurella/django-fakery/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247608151,"owners_count":20965952,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["creation-methods","django","testing"],"created_at":"2024-07-30T21:00:54.019Z","updated_at":"2025-04-07T07:08:20.245Z","avatar_url":"https://github.com/fcurella.png","language":"Python","funding_links":[],"categories":["Third-Party Packages"],"sub_categories":["Testing","Models"],"readme":"Django-fakery\n=============\n\n.. image:: https://badge.fury.io/py/django-fakery.svg\n    :target: https://badge.fury.io/py/django-fakery\n\n.. image:: https://travis-ci.org/fcurella/django-fakery.svg?branch=master\n    :target: https://travis-ci.org/fcurella/django-fakery\n\n\n.. image:: https://coveralls.io/repos/fcurella/django-fakery/badge.svg?branch=master\u0026service=github\n  :target: https://coveralls.io/github/fcurella/django-fakery?branch=master\n\nAn easy-to-use implementation of `Creation Methods`_ (aka Object Factory) for Django, backed by ``Faker``.\n\n.. _Creation Methods: http://xunitpatterns.com/Creation%20Method.html\n\n``django_fakery`` will try to guess the field's value based on the field's name and type.\n\nInstallation\n------------\n\nInstall with::\n\n    $ pip install django-fakery\n\nQuickStart\n----------\n\n.. code-block:: python\n\n    from django_fakery import factory\n    from myapp.models import MyModel\n\n    factory.m(MyModel)(field='value')\n\nIf you're having issues with circular imports, you can also reference a model by using the ``M`` utility function:\n\n.. code-block:: python\n\n    from django_fakery import factory, M\n\n    factory.m(M(\"myapp.MyModel\"))(field=\"value\")\n\n\nIf you really don't want to import things, you could also just reference a model by using the ``\u003capp_label\u003e.\u003cModelName\u003e`` syntax. This is not encouraged, as it will likely break type-hinting:\n\n.. code-block:: python\n\n    from django_fakery import factory\n\n    factory.m(\"myapp.MyModel\")(field=\"value\")\n\n\nIf you use ``pytest``, you can use the ``fakery`` and ``fakery_shortcuts` fixtures\n(requires ``pytest`` and ``pytest-django``):\n\n.. code-block:: python\n\n    import pytest\n    from myapp.models import MyModel\n\n    @pytest.mark.django_db\n    def test_mymodel(fakery, fakery_shortcuts):\n        fakery.m(MyModel)(field=fakery_shortcuts.future_datetime())\n\n\n\nIf you'd rather, you can use a more wordy API:\n\n.. code-block:: python\n\n    from django_fakery import factory\n    from myapp.models import MyModel\n\n    factory.make(\n        MyModel,\n        fields={\n            'field': 'value',\n        }\n    )\n\nWe will use the short API thorough the documentation.\n\nThe value of a field can be any python object, a callable, or a lambda:\n\n.. code-block:: python\n\n    from django.utils import timezone\n    from django_fakery import factory\n    from myapp.models import MyModel\n\n    factory.m(MyModel)(created=timezone.now)\n\nWhen using a lambda, it will receive two arguments: ``n`` is the iteration number, and ``f`` is an instance of ``faker``:\n\n.. code-block:: python\n\n    from django.contrib.auth.models import User\n\n    user = factory.m(User)(\n        username=lambda n, f: 'user_{}'.format(n),\n    )\n\n``django-fakery`` includes some pre-built lambdas for common needs. See shortcuts_  for more info.\n\nYou can create multiple objects by using the ``quantity`` parameter:\n\n.. code-block:: python\n\n    from django_fakery import factory\n    from django.contrib.auth.models import User\n\n    factory.m(User, quantity=4)\n\nFor convenience, when the value of a field is a string, it will be interpolated with the iteration number:\n\n.. code-block:: python\n\n    from myapp.models import MyModel\n\n    user = factory.m(User, quantity=4)(\n        username='user_{}',        \n    )\n\nCustom fields\n-------------\n\nYou can add support for custom fields by adding your\ncustom field class and a function in ``factory.field_types``:\n\n.. code-block:: python\n\n  from django_fakery import factory\n\n  from my_fields import CustomField\n\n  def func(faker, field, count, *args, **kwargs):\n      return 43\n\n\n  factory.field_types.add(\n      CustomField, (func, [], {})\n  )\n\n\nAs a shortcut, you can specified any Faker function by its name:\n\n.. code-block:: python\n\n  from django_fakery import factory\n\n  from my_fields import CustomField\n\n\n  factory.field_types.add(\n      CustomField, (\"random_int\", [], {\"min\": 0, \"max\": 60})\n  )\n\nForeign keys\n------------\n\nNon-nullable ``ForeignKey`` s create related objects automatically.\n\nIf you want to explicitly create a related object, you can pass a factory like any other value:\n\n.. code-block:: python\n\n    from django.contrib.auth.models import User\n    from food.models import Pizza\n\n    pizza = factory.m(Pizza)(\n        chef=factory.m(User)(username='Gusteau'),\n    )\n\nIf 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``:\n\n.. code-block:: python\n\n    from django_fakery import factory, rels\n    from food.models import Pizza\n\n    pizza = factory.m(Pizza, quantity=5)(\n        chef=rels.SELECT,\n    )\n\n``django-fakery`` will always use the first instance of the related model, creating one if necessary.\n\nManyToManies\n------------\n\nBecause ``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.\n\nIf you want to explicitly create a related objects, you can pass a list as the field's value:\n\n.. code-block:: python\n\n    from food.models import Pizza, Topping\n\n    pizza = factory.m(Pizza)(\n        toppings=[\n            factory.m(Topping)(name='Anchovies')\n        ],\n    )\n\nYou can also pass a factory, to create multiple objects:\n\n.. code-block:: python\n\n    from food.models import Pizza, Topping\n\n    pizza = factory.m(Pizza)(\n        toppings=factory.m(Topping, quantity=5),\n    )\n\n.. _shortcuts:\n\nShortcuts\n---------\n\n``django-fakery`` includes some shortcut functions to generate commonly needed values.\n\n\n``future_datetime(end='+30d')``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nReturns 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'``\n\nValid units are:\n\n* ``'years'``, ``'y'``\n* ``'weeks'``, ``'w'``\n* ``'days'``, ``'d'``\n* ``'hours'``, ``'hours'``\n* ``'minutes'``, ``'m'``\n* ``'seconds'``, ``'s'``\n\nExample:\n\n.. code-block:: python\n\n    from django_fakery import factory, shortcuts\n    from myapp.models import MyModel\n\n    factory.m(MyModel)(field=shortcuts.future_datetime('+1w'))\n\n\n``future_date(end='+30d')``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nReturns 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'``\n\n``past_datetime(start='-30d')``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nReturns 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'``\n\n``past_date(start='-30d')``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nReturns 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'``\n\n\nLazies\n------\n\nYou can refer to the created instance's own attributes or method by using `Lazy` objects.\n\nFor example, if you'd like to create user with email as username, and have them always match, you could do:\n\n.. code-block:: python\n\n    from django_fakery import factory, Lazy\n    from django.contrib.auth.models import User\n\n    factory.m(auth.User)(\n        username=Lazy('email'),\n    )\n\n\nIf you want to assign a value returned by a method on the instance, you can pass the method's arguments to the ``Lazy`` object:\n\n.. code-block:: python\n\n    from django_fakery import factory, Lazy\n    from myapp.models import MyModel\n\n    factory.m(MyModel)(\n        myfield=Lazy('model_method', 'argument', keyword='keyword value'),\n    )\n\nPre-save and Post-save hooks\n----------------------------\n\nYou can define functions to be called right before the instance is saved or right after:\n\n.. code-block:: python\n\n    from django.contrib.auth.models import User\n    from django_fakery import factory\n\n    factory.m(\n        User,\n        pre_save=[\n            lambda u: u.set_password('password')\n        ],\n    )(username='username')\n\nSince settings a user's password is such a common case, we special-cased that scenario, so you can just pass it as a field:\n\n.. code-block:: python\n\n    from django.contrib.auth.models import User\n    from django_fakery import factory\n\n    factory.m(User)(\n        username='username',\n        password='password',\n    )\n\nGet or Make\n-----------\n\nYou can check for existance of a model instance and create it if necessary by using the ``g_m`` (short for ``get_or_make``) method:\n\n.. code-block:: python\n\n    from myapp.models import MyModel\n\n    myinstance, created = factory.g_m(\n        MyModel,\n        lookup={\n            'myfield': 'myvalue',\n        }\n    )(myotherfield='somevalue')\n\nIf you're looking for a more explicit API, you can use the ``.get_or_make()`` method:\n\n.. code-block:: python\n\n    from myapp.models import MyModel\n\n    myinstance, created = factory.get_or_make(\n        MyModel,\n        lookup={\n            'myfield': 'myvalue',\n        },\n        fields={\n            'myotherfield': 'somevalue',\n        },\n    )\n\nGet or Update\n-------------\n\nYou can check for existence of a model instance and update it by using the ``g_u`` (short for ``get_or_update``) method:\n\n.. code-block:: python\n\n    from myapp.models import MyModel\n\n    myinstance, created = factory.g_u(\n        MyModel,\n        lookup={\n            'myfield': 'myvalue',\n        }\n    )(myotherfield='somevalue')\n\nIf you're looking for a more explicit API, you can use the ``.get_or_update()`` method:\n\n.. code-block:: python\n\n    from myapp.models import MyModel\n\n    myinstance, created = factory.get_or_update(\n        MyModel,\n        lookup={\n            'myfield': 'myvalue',\n        },\n        fields={\n            'myotherfield': 'somevalue',\n        },\n    )\n\nNon-persistent instances\n------------------------\n\nYou can build instances that are not saved to the database by using the ``.b()`` method, just like you'd use ``.m()``:\n\n.. code-block:: python\n\n    from django_fakery import factory\n    from myapp.models import MyModel\n\n    factory.b(MyModel)(\n        field='value',\n    )\n\nNote that since the instance is not saved to the database, ``.build()`` does not support ManyToManies or post-save hooks.\n\nIf you're looking for a more explicit API, you can use the ``.build()`` method:\n\n.. code-block:: python\n\n    from django_fakery import factory\n    from myapp.models import MyModel\n\n    factory.build(\n        MyModel,\n        fields={\n            'field': 'value',\n        }\n    )\n\n\nBlueprints\n----------\n\nUse a blueprint:\n\n.. code-block:: python\n\n    from django.contrib.auth.models import User\n    from django_fakery import factory\n\n    user = factory.blueprint(User)\n\n    user.make(quantity=10)\n\nBlueprints can refer other blueprints:\n\n.. code-block:: python\n\n    from food.models import Pizza\n\n    pizza = factory.blueprint(Pizza).fields(\n            chef=user,\n        )\n    )\n\nYou can also override the field values you previously specified:\n\n.. code-block:: python\n\n    from food.models import Pizza\n\n    pizza = factory.blueprint(Pizza).fields(\n            chef=user,\n            thickness=1\n        )\n    )\n\n    pizza.m(quantity=10)(thickness=2)\n\nOr, if you'd rather use the explicit api:\n\n.. code-block:: python\n\n    from food.models import Pizza\n\n    pizza = factory.blueprint(Pizza).fields(\n            chef=user,\n            thickness=1\n        )\n    )\n\n    thicker_pizza = pizza.fields(thickness=2)\n    thicker_pizza.make(quantity=10)\n\n\nSeeding the faker\n-----------------\n\n.. code-block:: python\n\n    from django.contrib.auth.models import User\n    from django_fakery import factory\n\n    factory.m(User, seed=1234, quantity=4)(\n        username='regularuser_{}'\n    )\n\nCredits\n-------\n\nThe API is heavily inspired by `model_mommy`_.\n\n.. _model_mommy: https://github.com/vandersonmota/model_mommy\n\nLicense\n-------\n\nThis software is released under the MIT License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffcurella%2Fdjango-fakery","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffcurella%2Fdjango-fakery","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffcurella%2Fdjango-fakery/lists"}