1. 程式人生 > 程式設計 >Django 實現外來鍵去除自動新增的字尾‘_id’

Django 實現外來鍵去除自動新增的字尾‘_id’

django在使用外來鍵ForeignKey的時候,會自動給當前欄位後面新增一個字尾_id。

正常來說這樣並不會影響使用。除非你要寫原生sql,還有就是這個表是已經存在的,你只是把資料庫中的表映射回models。實際上django提供了這樣的一個關鍵字db_colnum來解決這個問題,你只需要:

f = models.ForeignKey(AnotherModel,db_column='f')

這樣就不會自動新增_id這個字尾了。

文件中是這麼解釋的:

The name of the database column to use for this field. If this isn't given,Django will use the field's name.

If your database column name is an SQL reserved word,or contains characters that aren't allowed in Python variable names – notably,the hyphen – that's OK. Django quotes column and table names behind the scenes.

https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column

以上這篇Django 實現外來鍵去除自動新增的字尾‘_id'就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。