Model Bakery

1.23.4 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `baker.make()` to create single or multiple Django model instances, specify field values, and use custom generators. For a real application, you would replace `MyModel` with your actual Django model.

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

view raw JSON →