Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 556
Martin Avatar asked Nov 16 '12 14:11

Martin


People also ask

What is __ Str__ in Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

What is field name in Django?

Python | Relational fields in Django models. Django model data types and fields list. TextField – Django Models. DateTimeField – Django Models. DateTimeField – Django Forms.

What is primary key in Django model?

If you'd like to specify a custom primary key, specify primary_key=True on one of your fields. If Django sees you've explicitly set Field.primary_key , it won't add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).


2 Answers

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). :-)

like image 157
zonky Avatar answered Oct 02 '22 07:10

zonky


Field objects have a primary_key attribute

for field in CustomPK._meta.fields:   print field.primary_key   print field.name   # True # primary # False # payload 
like image 35
dm03514 Avatar answered Oct 02 '22 08:10

dm03514