开发者

Django ManyToManyField error

开发者 https://www.devze.com 2023-02-22 13:04 出处:网络
I am using Django\'s ManyToManyField, and when i try to add data to it, i get the following error: Traceback 开发者_开发百科(most recent call last):

I am using Django's ManyToManyField, and when i try to add data to it, i get the following error:

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"

I am using Django 1.3, and i following is a part of my code:

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")

This is where the error occurs:

G = Genre.objects.get(gid = obj[i]['id'])
print G.name, G.gid
movie.genre.add( G )

It is guaranteed that obj[i]['id'] will be found inside Genre. Can someone please help me?


You need to save the movie instance after creating it, before you can add m2m relations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号