Get name of primary field of Django model
Question:
In Django, every model has a pseudo attribute pk
, that points to the field that is declared as primary key.
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.
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
So my question is, how can I get the name of the field, that is the primary key?
Answers:
Field objects have a primary_key
attribute
for field in CustomPK._meta.fields:
print field.primary_key
print field.name
# True
# primary
# False
# payload
You will also have an attribute “name” on the pk-attribute. This seems to hold the name of the Field.
CustomPK._meta.pk.name
In my case I get the value “id” as result (like it should). 🙂
In Django, every model has a pseudo attribute pk
, that points to the field that is declared as primary key.
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.
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
So my question is, how can I get the name of the field, that is the primary key?
Field objects have a primary_key
attribute
for field in CustomPK._meta.fields:
print field.primary_key
print field.name
# True
# primary
# False
# payload
You will also have an attribute “name” on the pk-attribute. This seems to hold the name of the Field.
CustomPK._meta.pk.name
In my case I get the value “id” as result (like it should). 🙂