当我将书籍模型添加到数据库中,然后在 SQL 数据库浏览器中查看书籍表时,它显示 id 字段为空白。
这很奇怪,因为我的表中有 1000 个项目。我不知道发生了什么,因为其中约 390 人的 ID 已填充。其他人的 id 为空白。
id 字段不应该本质上是主键吗?在某些情况下而不是其他情况下如何填充它。
注1:过去我手动删除了记录——不确定这是否是个问题。注意 2:当 Iprint "newbook id:", repr(newbook.id)
时,id 与 SQL 数据库浏览器中看到的主键不同。
这就是我所看到的:
相关代码如下:
模型:
class Books (models.Model):
bookname=models.CharField(_('bookname'), max_length=255)
publisher=models.CharField(_('publisher'), max_length=255)
description=models.TextField(_('description'), blank=True)
coverart = models.ImageField(upload_to="art", blank=True, null=True)
source=models.TextField(blank=True) #source of where it came from
last_updated=models.DateTimeField(_('added'), default=datetime.now)
category_id=models.ManyToManyField(Category, related_name='cat')
model = models.ManyToManyField ('model', related_name = 'model')
shortdesc=models.TextField(_('description'), blank=True)
url = models.TextField(_('url'), blank=True)
uid = models.IntegerField()`
保存一本书的代码:
try:
exists = Books.objects.get(bookname=bookname)
except Books.DoesNotExist:
print "book does not exist -- adding now"
newbook=Books(bookname=bookname, uid = uid, source='Mysourceofbooks', publisher=publisher, description = description, shortdesc=shortdesc, url = url)
newbook.save()
for cat in category_ids:
newbook.category_id.add(cat)
else:
print "log: we found the book in the DB already"`