I always get a primary column as Id in the Django model. Is there any possibility to change. For ex. for City table I want to have a Primary Key column as city_id
.
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.
By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.
It doesn't matter. pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields.
AutoField. An IntegerField that automatically increments according to available IDs. You usually won't need to use this directly; a primary key field will automatically be added to your model if you don't specify otherwise.
city_id = models.AutoField(primary_key=True)
The answer is YES,
Something like this:
city_id = models.PositiveIntegerField(primary_key=True)
Here, you are overriding the id
. Documentation here
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.
Alternatively, You can always define a model property and use that . Example
class City(models.Model) #attributes @property def city_id(self): return self.id
and access it as city.city_id
where you would normally do city.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With