1👍
✅
This is a question about ManyToMany fields, not ForeignKeys.
For an M2M, you can’t do it as part of create
– you need to set it afterwards (because an m2m relationship is really a record in a third, linking, table, so you need the PK of the original model which you only get after it is created).
john = speaker.objects.create(
name = "John Smith",
email = "john@john.com"
)
unit = talk.objects.create(
title = "Writing unit tests",
summary = "How to write unit tests",
)
unit.speakers.add(john)
I should also note that this is not a good unit test. The mechanics of model instance creation and saving is well tested by Django’s own tests. Your unit tests should test your actual logic.
Source:stackexchange.com