model-bakers / model_bakery

Object factory for Django
https://model-bakery.readthedocs.io/en/latest/
Other
846 stars 85 forks source link

`baker.make()` with `_bulk_create=True` fails for M2M-fields that have a reverse_name #489

Open richardebeling opened 3 months ago

richardebeling commented 3 months ago

Follow-Up to #385, which was fixed in #486. When specifying values for a M2M field that has a reverse_name, baker currently tries to create an instance of the through-model using the related name when _bulk_create=True is passed.

Add this test case to TestCreateM2MWhenBulkCreate. Note that it is very similar to test_create, just the model used is switched from Classroom to Store, since Store.customers specifies a related_name.

def test_create_with_field_with_related_name(self):
    person = baker.make(models.Person)

    with self.assertNumQueries(11):
        baker.make(
            models.Store, customers=[person], _quantity=10, _bulk_create=True
        )
    s1, s2 = models.Store.objects.all()[:2]
    assert list(s1.customers.all()) == list(s2.customers.all()) == [person]

The test fails with this error:

___TestCreateM2MWhenBulkCreate.test_create_with_field_with_related_name ___
tests/test_baker.py:1090: in test_create_with_field_with_related_name
    baker.make(
model_bakery/baker.py:131: in make
    return bulk_create(baker, _quantity, _save_kwargs=_save_kwargs, **attrs)
model_bakery/baker.py:857: in bulk_create
    [
model_bakery/baker.py:858: in <listcomp>
    through_model(
../../.local/lib/python3.10/site-packages/django/db/models/base.py:567: in __init__
    raise TypeError(
E   TypeError: Store_customers() got unexpected keyword arguments: 'favorite_stores'

Versions