aayushdagra
aayushdagra

Reputation: 189

django models.ForeignKey behavior

I have 2 classes in models.py : PRODUCTS and PARTS.

class PRODUCTS (models.Model):
    productid = models.IntegerField(primary_key = True)
    ...

class PARTS(models.Model):
    partid= models.IntegerField(primary_key = True)
    productid = models.IntegerField(null = True, blank = True)
    ...

They are corespond with my two DB tables.

    CREATE TABLE `PRODUCTS` (
       `productid ` int(11) NOT NULL,
       ... )

    CREATE TABLE `PARTS` (
       `partid` int(11) NOT NULL,
       `productid ` int(11) NOT NULL,
        PRIMARY KEY  (`partid`),
        KEY `main_5cae8fa2` (`productid `),
        CONSTRAINT `productid_id_6ce77021aa` FOREIGN KEY (`productid `) REFERENCES `PRODUCTS` (`productid `)
       ... )

In django I need to get the parts of a specific product so I changed PARTS class to be:

class PARTS(models.Model):
    partid = models.IntegerField(primary_key = True)
    productid = models.ForeignKey(PRODUCTS, related_name = 'parts')

for example this I should be able to access the parts of product 100 like this:

products = PRODUCTS.objects.get(100)
x = products.parts

However this change causes a problem as django auto add _id to the column name meaning he is no longer looking for productid now he is looking for productid_id

(1054, "Unknown column 'PARTS.productid_id' in 'field list'")

How can I disable the auto add of _id ? changing my column name will take hours there are so many places that insert/delete/update this table.

Upvotes: 0

Views: 574

Answers (1)

Tim
Tim

Reputation: 1357

You can manually specify an column name for a model field with the db_column setting.

class PARTS(models.Model):
    partid = models.IntegerField(primary_key = True)
    productid = models.ForeignKey(PRODUCTS, related_name = 'parts', db_column='productid')

Upvotes: 1

Related Questions