[Fixed]-Django: how to make two models share one unique primary key

0👍

I think the best solution would be to make a parent class and make both Asset and Equipment inherit from it.

For example, you could make a BaseAsset class with an asset_id unique field. As both classes will share the same table for asset_id, there’s no way they will collide.

class BaseAsset(models.Model):
    asset_id = models.IntegerField(unique=True)

class Asset(BaseAsset):
    .
    .
    .

class Equipment(BaseAsset):
    .
    .
    .

1👍

This doesn’t sound like a good idea at all. If Asset and Equipment have different fields, then they should be different classes.
If you subclass to make them share a key, you will end up with a database that doesn’t reflect reality, at all.
It would be better to enforce uniqueness in your view than to corrupt your schema.

👤Rob L

Leave a comment