In Django, is there a way (function) to test if a model field is primary key ( pk
)?
For instance, my model is:
class Gender(models.Model):
name = models.CharField(max_length=50, primary_key=True)
def __str__(self):
return self.name
Is there a function to test for name being primary key?
You can use get_field
from the model meta api , then check the primary_key
attribute, which will be True
for primary keys.
field_name = 'name'
field = MyModel._meta.get_field(field_name)
field.primary_key
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.