{"id":8327,"library":"django-model-mommy","title":"Django Model Mommy","description":"Django Model Mommy is a smart object creation facility for Django, providing simple and flexible ways to generate test data for models without having to manually define all fields. It significantly simplifies fixture creation for tests and development. The current version is 2.0.0, with its last release in 2021, indicating it is in maintenance mode rather than active development.","status":"maintenance","version":"2.0.0","language":"en","source_language":"en","source_url":"https://github.com/makinacorpus/django-model-mommy","tags":["django","testing","fixtures","data-generation","orm"],"install":[{"cmd":"pip install django-model-mommy","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core functionality is built on Django's ORM and model system.","package":"Django","optional":false}],"imports":[{"note":"The top-level module is `model_mommy`, not just `mommy`.","wrong":"from mommy import mommy","symbol":"mommy","correct":"from model_mommy import mommy"},{"symbol":"Recipe","correct":"from model_mommy.recipe import Recipe"}],"quickstart":{"code":"import os\nimport django\nfrom django.conf import settings\nfrom django.db import models\n\n# Minimal Django setup for standalone execution\nif not settings.configured:\n    os.environ.setdefault('DJANGO_SETTINGS_MODULE', __name__)\n    settings.configure(\n        INSTALLED_APPS=[\n            'django.contrib.auth',\n            'django.contrib.contenttypes',\n            'myapp' # assuming 'myapp' will be created\n        ],\n        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},\n        DEBUG=True\n    )\n    django.setup()\n\n# Define a simple Django model for demonstration\nclass Author(models.Model):\n    name = models.CharField(max_length=100, unique=True)\n    email = models.EmailField()\n    bio = models.TextField(blank=True, null=True)\n\n    class Meta:\n        app_label = 'myapp'\n\n    def __str__(self):\n        return self.name\n\n# To ensure the model is 'migrated' in memory for mommy\nfrom django.core.management import call_command\ncall_command('makemigrations', 'myapp', interactive=False, verbosity=0)\ncall_command('migrate', 'myapp', interactive=False, verbosity=0)\n\nfrom model_mommy import mommy\n\n# 1. Create a single Author instance with random data\nauthor_1 = mommy.make(Author)\nprint(f\"1. Created author (random): {author_1.name} <{author_1.email}>\")\n\n# 2. Create multiple Author instances (e.g., 3)\nauthors = mommy.make(Author, _quantity=3)\nprint(f\"2. Created {len(authors)} authors (random). Example: {authors[0].name}\")\n\n# 3. Create an Author instance with specific attributes\nspecific_author = mommy.make(Author, name='Jane Doe', email='jane.doe@example.com')\nprint(f\"3. Created author (specific): {specific_author.name} <{specific_author.email}>\")\n\n# 4. Use mommy.prepare() to create an unsaved instance\nunsaved_author = mommy.prepare(Author, name='Unsaved Sam')\nprint(f\"4. Prepared unsaved author: {unsaved_author.name} (not in DB yet)\")\n\n# You can then save it manually if needed\nunsaved_author.save()\nprint(f\"   Saved unsaved author to DB.\")","lang":"python","description":"This quickstart demonstrates how to use `mommy.make()` and `mommy.prepare()` to create Django model instances. It includes a minimal, runnable Django setup for demonstration purposes outside of a full project. In a real Django project (e.g., tests), you would typically import your models directly and skip the setup part."},"warnings":[{"fix":"Ensure your project runs on Python 3.x and Django 2.2+ before upgrading `django-model-mommy` to version 2.0.0 or later.","message":"Python 2 and Older Django Versions No Longer Supported. Version 2.0.0 and above dropped support for Python 2.x and Django versions prior to 2.2.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Use `make()` when you need the object persisted and accessible via database queries (e.g., in integration tests). Use `prepare()` when you need an object for validation or to mock database interactions without actually hitting the database.","message":"`mommy.make()` vs. `mommy.prepare()`: `make()` saves the created object(s) to the database, including related objects, while `prepare()` creates an unsaved model instance, useful for validation or manual saving.","severity":"gotcha","affected_versions":"All"},{"fix":"For unique fields, either provide an explicit unique value (e.g., `mommy.make(MyModel, unique_field='my_specific_value')`) or use a `Recipe` with generators like `mommy.recipe.seq` or custom functions to guarantee uniqueness.","message":"Unique Field Collisions: `mommy` generates random data for fields, which can lead to `IntegrityError` if a generated value for a `unique=True` field already exists in the database. This is more common with simple data types or small ranges.","severity":"gotcha","affected_versions":"All"},{"fix":"Remove any calls to `mommy.seed()`. For controlling randomness, use Python's standard `random.seed()` if needed for reproducibility.","message":"The `mommy.seed()` function for seeding the random number generator was removed in version 2.0.0.","severity":"deprecated","affected_versions":"<2.0.0"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure you have the correct package installed: `pip install django-model-mommy`. If you mistakenly installed `model-mommy`, uninstall it first (`pip uninstall model-mommy`).","cause":"You likely installed the older, unmaintained `model-mommy` package instead of `django-model-mommy`, or the package is not installed at all.","error":"ModuleNotFoundError: No module named 'model_mommy'"},{"fix":"Provide a guaranteed unique value explicitly: `mommy.make(MyModel, unique_field='a_unique_value')`. Alternatively, for complex scenarios, define a `Recipe` that uses `mommy.recipe.seq` or custom functions to generate unique data for that field.","cause":"`mommy.make()` attempted to save a model instance where a randomly generated value for a `unique=True` field (or `unique_together`) already existed in the database.","error":"django.db.utils.IntegrityError: (1062, \"Duplicate entry '...' for key '...' (or similar for other DB backends)\")"},{"fix":"Ensure you are using the correct import: `from model_mommy import mommy`.","cause":"Incorrect import statement. The `mommy` factory object is directly available at the top level of the `model_mommy` module.","error":"AttributeError: module 'model_mommy' has no attribute 'mommy'"},{"fix":"Ensure your environment is a proper Django context (e.g., a test suite, `manage.py shell`) or that your standalone script explicitly calls `django.setup()` after setting `DJANGO_SETTINGS_MODULE`.","cause":"`django-model-mommy` functions, which interact with Django's models, are being called in a Python script or environment where Django's application registry has not been fully initialized.","error":"django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet."}]}