Search code examples
pythonsqldjangomodels

django model foreign key created index


I am creating models in django. This is my config in the models file. I want to create a table governmentoffical that references counties and citizen. However, when I ran manage.py sqlal, it changed my column name in government official tables.

class counties(models.Model):
    name = models.CharField(max_length=50, primary_key=True, unique=True)
    population = models.IntegerField()
    governer = models.CharField(max_length=75)

class citizen(models.Model):
    ssn = models.CharField(max_length=40, primary_key=True)
    citizen_name = models.CharField(max_length=50, unique=True)
    age = models.IntegerField()
    income = models.IntegerField()
    username = models.CharField(max_length=30)
    password = models.CharField(max_length=30)

class governmentOfficial(models.Model):
    countyName = models.ForeignKey(counties, primary_key=True)
    offical_name = models.ForeignKey(citizen, to_field='citizen_name')
    position = models.CharField(max_length=50)
    year_elected = models.IntegerField(max_length=4)
    party = models.CharField(max_length=25)
    county_username=models.CharField(max_length=20)
    county_password=models.CharField(max_length=20)

Here is my sql output.

CREATE TABLE `troywebsite_governmentofficial` (
    `countyName_id` varchar(50) NOT NULL PRIMARY KEY,
    `offical_name_id` varchar(50) NOT NULL,
    `position` varchar(50) NOT NULL,
    `year_elected` integer NOT NULL,
    `party` varchar(25) NOT NULL,
    `county_username` varchar(20) NOT NULL,
    `county_password` varchar(20) NOT NULL
)
;
ALTER TABLE `troywebsite_governmentofficial` ADD CONSTRAINT `countyName_id_refs_name_2c9a2c94` FOREIGN KEY (`countyName_id`) REFERENCES `troywebsite_counties` (`name`);
ALTER TABLE `troywebsite_governmentofficial` ADD CONSTRAINT `offical_name_id_refs_citizen_name_6f795c2a` FOREIGN KEY (`offical_name_id`) REFERENCES `troywebsite_citizen` (`citizen_name`);

CREATE INDEX `troywebsite_governmentofficial_effdd6a5` ON `troywebsite_governmentofficial` (`offical_name_id`);
CREATE INDEX `troywebsite_solider_c5b4e228` ON `troywebsite_solider` (`solider_name_id`);

Is there a way to take out the CREATE INDEX in governmentofficial, and leave to to be countyName and Official_name as the column?


Solution

  • You can use the db_column parameter to call the column whatever you like.

    https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column

    countyName = models.ForeignKey(counties, primary_key=True, db_column='whatever')