Model Bakery
Model Bakery is a smart object creation facility for Django, designed to simplify the creation of test data and mock objects for your Django models. It is currently at version 1.23.4 and maintains an active development cycle with frequent patch and minor releases, ensuring support for recent Django and Python versions.
Warnings
- breaking Model Bakery dropped support for Python 3.8 and 3.9 in v1.21.0, and Django 5.0 and 5.1 in v1.23.0.
- gotcha Prior to v1.23.0, using `related()` with ForeignKey relations could inadvertently create duplicate parent entities.
- gotcha The `_bulk_create` flag had known issues with ManyToManyField using custom `through` models (fixed in v1.23.1) and failing to set M2M fields on FK-related objects (fixed in v1.23.4).
- deprecated The `seq` utility was moved from `model_bakery.recipe` to `model_bakery.utils`.
- gotcha Overriding `AutoField` values via iterators when using `_quantity` could lead to hangs or unexpected behavior.
Install
-
pip install model-bakery
Imports
- baker
from model_bakery import baker
- Recipe
from model_bakery.recipe import Recipe
- seq
from model_bakery.utils import seq
Quickstart
from django.db import models
from model_bakery import baker
# Define a simple Django model for demonstration
class MyModel(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField(default=1)
class Meta:
app_label = 'myapp' # Required for standalone execution without full Django app setup
def __str__(self):
return f"{self.name} ({self.age})"
# Create a single instance of MyModel with default values
instance = baker.make(MyModel)
print(f"Created single instance: {instance}")
# Create multiple instances
instances = baker.make(MyModel, _quantity=3)
print(f"\nCreated {len(instances)} instances:")
for inst in instances:
print(f"- {inst}")
# Create an instance with specific attribute values
specific_instance = baker.make(MyModel, name='Jane Doe', age=25)
print(f"\nCreated specific instance: {specific_instance}")
# Using a custom generator for a field
from model_bakery.generators import gen_integer
custom_age_instance = baker.make(MyModel, age=gen_integer(min_value=40, max_value=50))
print(f"\nCreated custom age instance: {custom_age_instance}")