[Fixed]-How to give foreign key name in django

22👍

By default, Django populates column’s name by appending _id to the field name you define in your model. You must explicitly specify column’s name using db_column property as follows:

writer = models.ForeignKey(Bbs_User, db_column='writer_sid')

10👍

Foreign Keys are automatically named that way by the framework, but you can change the name of the column using db_column parameter when declaring the field:

myKey = models.ForeignKey('MyRelatedModel', db_column='my_column_name')

Update: I should mention that the automatic naming has some advantages when making queries: if you call myBbsInstance.writer.id you would get a RelatedManager instance that you need to resolve, hitting the database, to just getting the id, while calling myBbsInstance.writer_id just return the number inserted in the column, without a database hit. It’s very mnemonic.

Leave a comment