简体   繁体   English

如何在Django中提供外键名称

[英]How to give foreign key name in django

I built a model called bbs with a reference to User table. 我建立了一个名为bbs的模型,该模型引用了User表。

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客户端中,我查看了Bbs表的布局。

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'. 此时,我想知道为什么字段名称是'writer_id'。
I think the field name must be 'writer_sid' or 'writer'. 我认为字段名称必须为“ writer_sid”或“ 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. 默认情况下,Django通过在您在模型中定义的字段名称后附加_id来填充列的名称。 You must explicitly specify column's name using db_column property as follows: 您必须使用db_column属性显式指定列的名称,如下所示:

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: 框架通过这种方式自动为外键命名,但是在声明字段时,可以使用db_column参数更改列的名称:

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. 更新:我应该提一下,自动命名在查询时有一些优势:如果调用myBbsInstance.writer.id您将得到一个需要解析的RelatedManager实例,在调用myBbsInstance.writer.id ,将其击中数据库即可获取ID myBbsInstance.writer_id仅返回插入列中的数字,而没有数据库命中。 It's very mnemonic. 这很容易记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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