python - How to set value of a ManyToMany field in Django? -
while learning django web programming,i faced problem. searched google , django's official website biut not find answer. please me.
system environment:
- fedora 18
- python 2.7
- django 1.5.1
- eclipse + pydev
runtime: django's development server
i have models includes manytomany field.when set value django's admin panel,everything goes well. codes below of models:
class posts(models.model): post_authorid = models.integerfield(verbose_name=u'authorid') post_date = models.datetimefield(auto_now_add=true,verbose_name=u'postdate') post_date_modified = models.datetimefield(auto_now=true,verbose_name=u'lastmodifiedtime') post_content = models.textfield(verbose_name=u'content') post_title = models.charfield(max_length=50,verbose_name=u'title') post_name = models.charfield(max_length=50,blank=true,verbose_name=u'shortname') post_cover = models.charfield(max_length=200,verbose_name=u'coverurl') post_introduction = models.charfield(max_length=500,blank=true,verbose_name=u'introduction') post_status = models.foreignkey(status,verbose_name=u'status') comment_status = models.booleanfield(verbose_name=u'show_comments') post_password = models.charfield(max_length=20,blank=true,verbose_name=u'passwd') post_tagid = models.manytomanyfield(tags,verbose_name=u'tag') post_threadtypeid = models.foreignkey(threadtypes,verbose_name=u'threadtype') post_comment_conut = models.integerfield(verbose_name=u'commentscount') post_comments = models.manytomanyfield(comments,blank=true,verbose_name=u'comment') def __unicode__(self): return u"%s %s %s" % (self.id,self.post_title,self.post_date) class meta: ordering = ['post_date'] class tags(models.model): tagname = models.charfield(max_length=20,verbose_name=u'标签名称') def __unicode__(self): return u"%s %s" % (self.id,self.tagname) class meta: ordering = ['id']
in python shell,i input:
post = posts() post.post_tagid = tags.objects.get(id='1')
then django rasise http 500 error:
object needs have value field "posts" before many-to-many relationship can used.
but,when use :
post= posts.objects.get(id='1')
note- have input posts object django admin
then,when use
post.post_tagid = tags.objects.get(id='1')
everything goes well.
q:how can add manytomany field without error raising?
it looks problem here you're trying add m2m table before it's created in database.
when run post = posts()
create object in memory, not in database. when try add new entry m2m table there nothing reference. (remember declaring m2m field causes creation of new table records point both ends of relationship.)
the solution run post.save()
before trying add m2m table. (the django admin doing behind scenes.)
so try this:
post = posts() # set post (title, name, etc.) post.save() # adds new entry posts table post.post_tagid.add(tag) # post exists in db should work
Comments
Post a Comment