Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using related with FK relation creates a duplicate entity #397

Open
amureki opened this issue Mar 16, 2023 · 1 comment
Open

Using related with FK relation creates a duplicate entity #397

amureki opened this issue Mar 16, 2023 · 1 comment
Labels
bug Something isn't working

Comments

@amureki
Copy link
Collaborator

amureki commented Mar 16, 2023

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
@amureki amureki added the bug Something isn't working label Mar 16, 2023
@amureki amureki changed the title Using related with FK relation creates duplicate entity Using related with FK relation creates a duplicate entity Mar 16, 2023
@amureki
Copy link
Collaborator Author

amureki commented Mar 16, 2023

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant