2012-06-12 74 views
1

當我向數據庫中添加書籍模型,然後在SQL數據庫瀏覽器中查看書籍表格時,它將ID字段顯示爲空白。將模型保存到數據庫後的空ID

這很奇怪,因爲我在表中有1000個項目。我不知道發生了什麼事,因爲約有390人擁有自己的身份證。其他人的ID爲空白。

不應該id字段本質上是主鍵?在某些情況下它怎麼會被填充,而不是其他情況。

注意1:過去我手動刪除記錄 - 不確定是否可能是一個問題。 注2:當我print "newbook id:", repr(newbook.id)時,id與在SQL數據庫瀏覽器中看到的主鍵不同。

這是我所看到的:

enter image description here

相關的代碼如下:

型號:

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"` 
+0

你在說什麼「id」? Django添加了'id'字段?或者你的'uid'字段?你能舉一個例子來說明帶有「空ID」的書嗎? –

+0

是Django添加的'id'字段。代碼是我做newbook.save時的第二段代碼() – user1328021

+0

所以,如果你使用'newbook = Book(...); newbook.save();打印「newbook id:」,repr(newbook.id)',你會看到'newbook id:None'? –

回答

2

根據聊天中的討論:Book表中的id列以某種方式設法失去其作爲PRIMARY KEY的狀態。把它放回去,你應該很好去。

-1

首先,您可以使用功能get_or_create進行測試/保存模型。 它返回元組 - 對象,創建。

如果您可以使用新的ID保存對象:set object.pk爲None,並保存它。 在你的代碼中更瘋狂的認爲。 =>書籍是書籍的更好名稱。

你怎麼看這個:

for cat in category_ids: 
    print cat 
    newbook.category_id.add(cat) 

什麼是category_ids變量? 爲什麼將ManyToMany命名爲「category_id」?

+1

你的批評是有效的,但他們不回答這個問題。請不要使用「添加答案」按鈕發佈不是答案的內容。 –

+0

category_id是我從API中提取的整數 – user1328021

+0

而我實際上確實使用了'Book'。我很快就改變了模型,因爲我正在處理一些保密的事情,並且不想爲我正在處理的事情確定具體的變量。 – user1328021

相關問題