Django Model Mommy
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.
Common errors
-
ModuleNotFoundError: No module named '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.fixEnsure you have the correct package installed: `pip install django-model-mommy`. If you mistakenly installed `model-mommy`, uninstall it first (`pip uninstall model-mommy`). -
django.db.utils.IntegrityError: (1062, "Duplicate entry '...' for key '...' (or similar for other DB backends)")
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.fixProvide 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. -
AttributeError: module 'model_mommy' has no attribute 'mommy'
cause Incorrect import statement. The `mommy` factory object is directly available at the top level of the `model_mommy` module.fixEnsure you are using the correct import: `from model_mommy import mommy`. -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
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.fixEnsure 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`.
Warnings
- breaking 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.
- gotcha `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.
- gotcha 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.
- deprecated The `mommy.seed()` function for seeding the random number generator was removed in version 2.0.0.
Install
-
pip install django-model-mommy
Imports
- mommy
from mommy import mommy
from model_mommy import mommy
- Recipe
from model_mommy.recipe import Recipe
Quickstart
import os
import django
from django.conf import settings
from django.db import models
# Minimal Django setup for standalone execution
if not settings.configured:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', __name__)
settings.configure(
INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'myapp' # assuming 'myapp' will be created
],
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
DEBUG=True
)
django.setup()
# Define a simple Django model for demonstration
class Author(models.Model):
name = models.CharField(max_length=100, unique=True)
email = models.EmailField()
bio = models.TextField(blank=True, null=True)
class Meta:
app_label = 'myapp'
def __str__(self):
return self.name
# To ensure the model is 'migrated' in memory for mommy
from django.core.management import call_command
call_command('makemigrations', 'myapp', interactive=False, verbosity=0)
call_command('migrate', 'myapp', interactive=False, verbosity=0)
from model_mommy import mommy
# 1. Create a single Author instance with random data
author_1 = mommy.make(Author)
print(f"1. Created author (random): {author_1.name} <{author_1.email}>")
# 2. Create multiple Author instances (e.g., 3)
authors = mommy.make(Author, _quantity=3)
print(f"2. Created {len(authors)} authors (random). Example: {authors[0].name}")
# 3. Create an Author instance with specific attributes
specific_author = mommy.make(Author, name='Jane Doe', email='jane.doe@example.com')
print(f"3. Created author (specific): {specific_author.name} <{specific_author.email}>")
# 4. Use mommy.prepare() to create an unsaved instance
unsaved_author = mommy.prepare(Author, name='Unsaved Sam')
print(f"4. Prepared unsaved author: {unsaved_author.name} (not in DB yet)")
# You can then save it manually if needed
unsaved_author.save()
print(f" Saved unsaved author to DB.")