$ show model-bakers/model_bakery
Model Bakery is a mature, well-tested Python library for Django that automates the creation of test fixtures by generating random data for model instances. Its core API (`baker.make()`, `baker.prepare()`, recipes) eliminates boilerplate in test setup while remaining flexible through overrides, sequences, callables, and custom generators. The codebase demonstrates high craftsmanship: a clean separation between field/value generation (`random_gen.py`), attribute classification (`Baker._classify_attrs`), and recipe composition (`recipe.py`). It supports nearly all Django field types, relationships (FK, M2M, O2O, GFK), bulk creation, multi-database setups, and model validation (`_full_clean`). The library is actively maintained with modern tooling (uv, ruff, ty, tox-uv) and follows semantic versioning.
The LLM identified 4 files worth highlighting for reuse:
The `Baker._classify_attrs()` method partitions keyword arguments into groups (reverse-FK, reverse-O2O, auto-now, GFK) before instance creation. It is a pure, database-free function that can be extracted and reused in any project needing to segregate field types for different processing pipelines. The method is cleanly isolated and tested with zero database queries (see `test_baker.py::TestClassifyAttrs`).
The `seq()` function is a well-designed generator that yields sequential values for multiple types (int, float, Decimal, str, date, datetime, time) with configurable `increment_by`, `start`, and `suffix`. It handles datetime-aware incrementing via timedelta and validates parameters strictly. The implementation is self-contained, fully independent of Django, and can be reused in any Python project that needs deterministic sequential data.
The `random_gen` module provides a comprehensive set of generator functions (e.g., `gen_integer`, `gen_string`, `gen_date`, `gen_related`, `gen_m2m`) that respect Django field constraints like `max_length`, `max_digits`, and allowed ranges. Each generator can be overridden or composed. The module is portable: the same generators could power any data generation task. Notable is the use of `required` attribute to extract field metadata, enabling dynamic parameterization.
The `Recipe` class provides a declarative, encapsulated way to define reusable test data templates with support for `foreign_key()`, `related()`, sequences, containers, and callables. The `_mapping()` method resolves inter-recipe references lazily, avoiding premature database access. The pattern of extending recipes (`extend()`) and overriding attributes at call time is clean and reusable for any object graph construction problem.