2014-11-04 48 views
0

我想創建一個模型,將數據庫中的兩個表連接起來。當寫外鍵是這樣的:如何將外鍵寫入其他模型的屬性?

fromnode = models.ForeignKey(znode.code) 
tonode = models.ForeignKey(znode.code) 

有一個錯誤:type object 'znode' has no attribute 'code',但在znode這樣的屬性:

class znode(models.Model): 
    code = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, primary_key=True) 

如何正確地寫這個?

+0

使用模型名'fromnode = models.ForeignKey(znode)'。 – 2014-11-04 19:40:51

回答

1

只需使用類名稱znode而不是znode.code。 Django自動爲每個模型添加一個id列,這些列將用作documentation中提到的參考。你

Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column.

也應該使用CamelCaseClassNames滿足pep8 coding style conventions

相關問題