Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the name of automatic primary key field in Django

By default, Django gives each model the following field:

id = models.AutoField(primary_key=True)

(https://docs.djangoproject.com/en/1.10/topics/db/models/#automatic-primary-key-fields)

This is great and convenient. However, I would like to know whether it is possible to change the name of the id field to more informative name, e.g., item_id. If this is indeed possible, how can I do that?

EDIT: From the answers I understand that it is impossible to do it without setting the primary key explicitly (which is what I wanted to know).

My model has many classes, and I think that it will be clearer to give more informative field names. Does it really matter?

like image 897
Gari BN Avatar asked Dec 18 '22 08:12

Gari BN


1 Answers

You just reference the source!

If you’d like to specify a custom primary key, just 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.

class MyModel(models.Model):
    item_id = models.AutoField(primary_key=True)
like image 86
nik_m Avatar answered Jan 01 '23 14:01

nik_m