model-bakers/model_bakery

Using `related` with FK relation creates a duplicate entity

amureki opened this issue · 1 comments

Describe the issue / To Reproduce

# baker_recipes.py
badger_without_owner = Recipe(Dog, breed="Badger")
badger_person = Recipe(Person, name='Badgerman', dog_set=related("badger_without_owner"))

# models.py
class Dog(models.Model):
    owner = models.ForeignKey("Person")

# tests.py
@pytest.mark.django_db
def test_related_models_recipes_reversed():
    person = baker.make_recipe("tests.generic.badger_person")
    assert Person.objects.count() == 1. # fails here, we are getting two `Person` objects
    assert person.dog_set.count() == 1

Versions

  • Python: 3.11
  • Django: 4.1
  • Model Bakery: 1.10.2

During the fields mapping, if there is a related, bakery directly executes make, which in the given example leads to Dog object being first in the queue, which recipe creates a owner=Person, as field is required. And then after we have Dog and Person, we finally created a main Person object we wanted.

Related code:

elif isinstance(v, related):
mapping[k] = v.make()

Long ago, in case of related we did prepare instead, which was changed to fix M2M relations:
berinhard/model_mommy@1e46b6a

On my first thought, I want to split related to related_fk and related_m2m, as their behaviour differs a bit, but there might be more to that.

Also, Django 4.1 might bring more fun to that, see #347.

@model-bakers/core, would you have any ideas/suggestions?