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()
测试程序
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))
报错
ValueError: "<Article: article4>" needs to have a value for field "id" before this many-to-many relationship can be used.
说明
id是数据库自增的,但是设置模型的时候使用了显示定义,bigauto,导致添加数据时也要显示指定id,不想指定,想通过数据库自己自增。
把id这一行去掉