How Model Bakery behaves?

By default, Model Bakery skips fields with null=True or blank=True. Also if a field has a default value, it will be used.

You can control which fields are filled in the following ways:

  1. Explicitly defining values, which override field defaults

# from "Basic Usage" page, assume all fields either null=True or blank=True
from model_bakery import baker

customer = baker.make('shop.Customer', enjoy_jards_macale=True, bio="A fan of Jards Malacé")
  1. Passing _fill_optional with a list of optional fields to include

customer = baker.make('shop.Customer', _fill_optional=['enjoy_jards_macale', 'bio'])
  1. Passing _fill_optional=True to include all optional fields on the model

customer = baker.make('shop.Customer', _fill_optional=True)

The _fill_optional options preserve field defaults. For example, default=None remains None, and default=list produces []. Fields without defaults use their generators. File and image fields also keep their defaults when _create_files=True.

To replace a default, pass an explicit value or callable. For example, for a model with a career array field and a main_image image field:

from model_bakery import baker
from model_bakery.random_gen import gen_image_field

employee = baker.make(
    'shop.Employee',
    career=['Developer'],
    main_image=gen_image_field,
    _create_files=True,
)

See Creating Files for file creation and cleanup.

When shouldn’t you let Baker generate things for you?

If you have fields with special validation, you should set their values by yourself.

Model Bakery should handle fields that:

  1. don’t matter for the test you’re writing;

  2. don’t require special validation (like unique, etc);

  3. are required to create the object.

The default generators for URLField and EmailField produce values of at least 17 and 13 characters, respectively. For fields with smaller max_length values, supply a value explicitly or use a custom generator.

Currently supported fields

  • BooleanField, IntegerField, BigIntegerField, SmallIntegerField, PositiveIntegerField, PositiveBigIntegerField, PositiveSmallIntegerField, FloatField, DecimalField

  • CharField, TextField, BinaryField, SlugField, URLField, EmailField, IPAddressField, GenericIPAddressField, ContentType

  • ForeignKey, OneToOneField, ManyToManyField (even with through model)

  • DateField, DateTimeField, TimeField, DurationField

  • FileField, ImageField

  • JSONField, ArrayField, HStoreField

  • CICharField, CIEmailField, CITextField

  • DecimalRangeField, IntegerRangeField, BigIntegerRangeField, DateRangeField, DateTimeRangeField

Require django.contrib.gis in INSTALLED_APPS:

  • GeometryField, PointField, LineStringField, PolygonField, MultiPointField, MultiLineStringField, MultiPolygonField, GeometryCollectionField

Custom fields

Model Bakery allows you to define generators methods for your custom fields or overrides its default generators. This can be achieved by specifying the field and generator function for the generators.add function. It can also be done by specifying the field and generator function in the BAKER_CUSTOM_FIELDS_GEN setting. Both can be the real python objects imported in settings or just specified as import path string.

Examples:

from model_bakery import baker

def gen_func():
    return 'value'

baker.generators.add('test.generic.fields.CustomField', gen_func)
# in the module code.path:
def gen_func():
    return 'value'

# in your tests.py file:
from model_bakery import baker

baker.generators.add('test.generic.fields.CustomField', 'code.path.gen_func')
# in your settings.py file:
BAKER_CUSTOM_FIELDS_GEN = {
    'test.generic.fields.CustomField': 'code.path.gen_func',
}

Customizing Baker

In some rare cases, you might need to customize the way Baker base class behaves. This can be achieved by creating a new class and specifying it in your settings files. It is likely that you will want to extend Baker, however the minimum requirement is that the custom class have make and prepare functions. In order for the custom class to be used, make sure to use the model_bakery.baker.make and model_bakery.baker.prepare functions, and not model_bakery.baker.Baker directly.

Examples:

# in the module code.path:
class CustomBaker(baker.Baker):
    def get_fields(self):
        return [
            field
            for field in super(CustomBaker, self).get_fields()
            if not isinstance(field, CustomField)
        ]

# in your settings.py file:
BAKER_CUSTOM_CLASS = 'code.path.CustomBaker'

Additionally, if you want to your created instance to be returned respecting one of your custom ModelManagers, you can use the _from_manager parameter as the example below:

movie = baker.make(Movie, title='Old Boys', _from_manager='availables')  # This will use the Movie.availables model manager

Save method custom parameters

If you have overwritten the save method for a model, you can pass custom parameters to it using Model Bakery. Example:

class ProjectWithCustomSave(models.Model):
    # some model fields
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL)

    def save(self, user, *args, **kwargs):
        self.created_by = user
        return super(ProjectWithCustomSave, self).save(*args, **kwargs)

#with model baker:
user = baker.make(settings.AUTH_USER_MODEL)
project = baker.make(ProjectWithCustomSave, _save_kwargs={'user': user})
assert user == project.user