我正在使用Django的ManyToManyField,当我尝试向其添加数据时,我收到以下错误:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/purav/Desktop/socmov/fbcon/models.py", line 165, in getMovieInfo
movie.genre.add( G )
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py", line 503, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py", line 563, in _add_items
(obj, self.instance._state.db, obj._state.db))
ValueError: Cannot add "<Genre: Genre object>": instance is on database "None", value is on database "default"
我正在使用Django 1.3,我跟随的是我的代码的一部分:
class Genre(models.Model):
gid = models.IntegerField(primary_key = True)
name = models.CharField(max_length = 20)
class Movie(models.Model):
mid = models.IntegerField(primary_key = True)
name = models.CharField(max_length = 100)
genre = models.ManyToManyField("Genre")
这是发生错误的地方:
G = Genre.objects.get(gid = obj[i]['id'])
print G.name, G.gid
movie.genre.add( G )
保证在类型中找到obj [i] ['id']。有人可以帮助我吗?
答案 0 :(得分:12)
您需要在创建影片后保存影片实例,然后才能添加m2m关系。