Django: How to save data to ManyToManyField?

Use the add method for related fields:

# using Model.object.create is a shortcut to instantiating, then calling save()
myMoveInfo = Movie_Info.objects.create(title="foo", overview='bar')
myMovieGenre = Movie_Info_genre.objects.create(genre="horror")
myMovieInfo.genres.add(myMoveGenre)

Unlike modifying other fields, both models must exist in the database prior to doing this, so you must call save before adding the many-to-many relationship. Since add immediately affects the database, you do not need to save afterwards.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)