[Django]-Django: How to save data to ManyToManyField?

89👍

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.

👤Jeff

Leave a comment