Django Model Mommy

2.0.0 · maintenance · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

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.

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.")

view raw JSON →