简体   繁体   中英

How to give foreign key name in django

I built a model called bbs with a reference to User table.

class Bbs_User(models.Model):
    sid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=45)
    #...

class Bbs(models.Model):
    sid = models.AutoField(primary_key=True)
    writer  = models.ForeignKey(Bbs_User)
    title = models.CharField(max_length=80)
    content = models.TextField()

    class Meta:
        db_table = 'Bbs'

    def __str__(self)
        return self.title

In mysql client, I have look into Bbs table layout.

mysql> desc Bbs
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+ 
| sid         | int(11)      | NO   | PRI | NULL    | auto_increment |
| writer_id   | int(11)      | NO   | MUL | NULL    |                |

At this point, I want to know why the field name is 'writer_id'.
I think the field name must be 'writer_sid' or 'writer'.

How can I fix it?

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')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM