[英]Get name of primary field of Django model
In Django, every model has a pseudo attribute pk
, that points to the field that is declared as primary key. 在Django中,每个模型都有一个伪属性
pk
,它指向声明为主键的字段。
class TestModel(models.Model):
payload = models.Charfield(max_length=200)
In this model, the pk
attribute would point to the implicit id
field, that is generated if no field is declared to be the primary. 在此模型中,
pk
属性将指向隐式id
字段,如果没有声明字段是主要字段,则生成该字段。
class CustomPK(models.Model)
primary = models.CharField(max_length=100, primary=True)
payload = models.Charfield(max_length=200)
In this model, the pk
attribute would point to the explicit defined primary key field primary
在此模型中,
pk
属性将指向显式定义的主键字段primary
So my question is, how can I get the name of the field, that is the primary key? 所以我的问题是,我怎样才能获得该字段的名称,即主键?
You will also have an attribute "name" on the pk-attribute. 您还将在pk-attribute上具有属性“name”。 This seems to hold the name of the Field.
这似乎保留了Field的名称。
CustomPK._meta.pk.name
In my case I get the value "id" as result (like it should). 在我的情况下,我得到值“id”作为结果(就像它应该)。 :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.