命名Django外键以请求正确的列

2024-10-02 00:21:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Django(我是新手)。我想定义一个外键,但我不知道该怎么做

我有一个名为stat_types的表:

class StatTypes(models.Model):
    stat_type = models.CharField(max_length=20)

现在,我想在totall_stats表中为django自动生成的stat_类型id定义一个外键。会是这样吗

    stat_types_id = models.ForeignKey('beta.StatTypes')

如果我想让stat_types表的stat_type列作为外键呢。那将是:

stat_type = models.ForeignKey('beta.StatTypes')

我想我的困惑在于不知道第二个模型中的列的名称,以便它知道第一个模型中的哪一列用作外键

谢谢


Tags: django模型idmodel定义modelstypestat
1条回答
网友
1楼 · 发布于 2024-10-02 00:21:19

给FK列名起什么名字并不重要。Django计算出它是一个外键,并将_id附加到该字段。所以这里不需要_id。我认为这已经足够好了

stat_type = models.ForeignKey('beta.StatTypes')

Doc says

It’s suggested, but not required, that the name of a ForeignKey field (manufacturer in the example above) be the name of the model, lowercase. You can, of course, call the field whatever you want.

相关问题 更多 >

    热门问题