Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to save data to ManyToManyField?

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) 
like image 875
starcorn Avatar asked Apr 28 '12 17:04

starcorn


People also ask

How does Django save data?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is super save Django?

When you overwrite a function (of a class) you can call the function of the parent class using super . The save function in the models records the instance in the database. The first super(Review, self). save() is to obtain an id since it is generated automatically when an instance is saved in the database.


1 Answers

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.

like image 161
Jeff Avatar answered Sep 20 '22 07:09

Jeff