djangodjango-modelspytestfixturespytest-django

How to add ManyToMany field with 'through' relation to fixtures?


In tests (fixtures) I want to add field with ManyToMany field with 'through' relation, i.e

my_field = models.ManyToManyField(SomeModel, through=AnotherModel).

Tried to add like regular ManyToManyField like:

object.my_field.add(my_field)

but it gives me this warning message: enter image description here

Also, tried this:

object.my_field.add(my_field, through_defaults=AnotherModel)

also didn't worked


Solution

  • You simply construct an AnotherModel object, so:

    AnotherModel.objects.create(firstmodel=object, somemodel=myfield)

    If the AnotherModel contains extra fields that have no default value, you will need to specify these as well.

    Or you can make use of .add(…) [Django-doc] where the through_defaults should contain a dictionary with values to pass to the AnotherModel:

    object.my_field.add(my_field, through_defaults={'field1': 14, 'field2': 25})

    See the Extra fields on many-to-many relationships section of the documentation for more information about the through_defaults. This contains an example like:

    beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)})

    In this example the members of the beatles object is a ManyToManyField with an intermediate model, and here we fill in date(1960, 8, 1) as value for date_joined in that model.