paulocheque / django-dynamic-fixture

A complete library to create dynamic model instances for testing purposes.
http://django-dynamic-fixture.readthedocs.io/
Other
391 stars 67 forks source link

[bugfix] ManyToManyField with through broken #17

Closed michaelmior closed 11 years ago

michaelmior commented 11 years ago

I have a model Foo with the following field

users = models.ManyToManyField(User, through='Bar')

The test case below causes an empty array to be printed.

class FooTest(TestCase):

    def test_foo(self):
        user = G(User)
        obj = G(Foo, players=[player])
        print(obj.users.all())

Looking into ddf.py, I see next_instance.save() is called if the related manager has no add method, the assumption being that through must have been specified on the model.

The problem is that while the instance is saved correctly, the relationship is never created. For me this is solved by adding the following after next_instance.save()

through_model = manytomany_field.through
through_instance = DynamicFixture(data_fixture=self.data_fixture) \
    .get(through_model, **{
        manytomany_field.source_field_name: instance,
        manytomany_field.target_field_name: next_instance
    })

This uses the same fixture to create an instance of the through model, establishing the relationship. I see there are currently no tests for through on ManyToManyField. Was the behaviour I'm seeing intended, or is this a bug?

paulocheque commented 11 years ago

Great! It appears to be a bug. I will review that and accept this pull request. Nice! Thanks! Regards

michaelmior commented 11 years ago

No problem :) Thanks for DDF! Maintaining fixture files is a pain.

paulocheque commented 11 years ago

I did a manual merge