Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id field in Model Django

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.

like image 706
syv Avatar asked Aug 05 '13 18:08

syv


People also ask

What is id in Django model?

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.

Do Django models have ID?

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.

Is PK and ID same in Django?

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.

What is AutoField in Django?

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.


Video Answer


2 Answers

city_id = models.AutoField(primary_key=True) 
like image 157
Akshar Raaj Avatar answered Sep 20 '22 01:09

Akshar Raaj


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

like image 39
karthikr Avatar answered Sep 19 '22 01:09

karthikr