Django: How to save data to ManyToManyField?

django, django-models

Solution

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.

Problem

I have a question concerning the following model. I want to populate the `ManyToManyField` from views.py instead of doing it from the Admin. But how do I add data to the `genres` field which is the `ManyToManyField`? views.py ``` content = Movie_Info(id = m_id, title = data[0].get('title'), overview = data[0].get('overview'), release_date = data[0].get('release_date'), ) content.save() ``` models.py ``` class Movie_Info_genre(models.Model): genre = models.CharField(max_length=100) class Movie_Info(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=100, blank=True, null=True) overview = models.TextField(blank=True, null=True) release_date = models.CharField(max_length=10, blank=True, null=True) genres = models.ManyToManyField(Movie_Info_genre) ```

Original source