當我向數據庫中添加書籍模型,然後在SQL數據庫瀏覽器中查看書籍表格時,它將ID字段顯示爲空白。將模型保存到數據庫後的空ID
這很奇怪,因爲我在表中有1000個項目。我不知道發生了什麼事,因爲約有390人擁有自己的身份證。其他人的ID爲空白。
不應該id字段本質上是主鍵?在某些情況下它怎麼會被填充,而不是其他情況。
注意1:過去我手動刪除記錄 - 不確定是否可能是一個問題。 注2:當我print "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"`
你在說什麼「id」? Django添加了'id'字段?或者你的'uid'字段?你能舉一個例子來說明帶有「空ID」的書嗎? –
是Django添加的'id'字段。代碼是我做newbook.save時的第二段代碼() – user1328021
所以,如果你使用'newbook = Book(...); newbook.save();打印「newbook id:」,repr(newbook.id)',你會看到'newbook id:None'? –