鍍金池/ 問(wèn)答/Python/ django model create報(bào)錯(cuò)

django model create報(bào)錯(cuò)

class Article(models.Model):

id=models.BigAutoField(primary_key=True)
title=models.CharField(max_length=32)
publishtime=models.DateTimeField(auto_now_add=True)
catalogs=models.ForeignKey(to='Catalog')
tags=models.ManyToManyField('Tag')
# content=models.OneToOneField(to='ArticleContent')
content=models.TextField()
測(cè)試程序

catalogs=models.Catalog.objects.all()
tags=models.Tag.objects.all()
c=random.choice(catalogs)
t=random.choice(tags)
models.Article.objects.create(title='article'+str(i),catalogs=c,tags=t,content=str(i))

報(bào)錯(cuò)
ValueError: "<Article: article4>" needs to have a value for field "id" before this many-to-many relationship can be used.

說(shuō)明
id是數(shù)據(jù)庫(kù)自增的,但是設(shè)置模型的時(shí)候使用了顯示定義,bigauto,導(dǎo)致添加數(shù)據(jù)時(shí)也要顯示指定id,不想指定,想通過(guò)數(shù)據(jù)庫(kù)自己自增。

回答
編輯回答
挽歌

manytomanyfield操作出了問(wèn)題

2018年9月21日 09:32
編輯回答
深記你

把id這一行去掉

2017年3月7日 09:22