[Answered ]-Django: assert 'Many-to-many' relation exists in test

2👍

Your model structure is wrong. You should only define the many-to-many on one side of the relationship; the other side is accessed via the reverse relationship.

Also, your assertion is wrong. You need to query the linked attributes via the project instance, not the Project class as a whole.

Finally, do you actually have some code before that assertion to validate and save the form? Otherwise nothing will have changed.

So:

self.assertTrue(form.is_valid())
saved_project = form.save()
self.assertTrue(saved_project.attributes_set.exists())

Leave a comment