Hansong Li
Hansong Li

Reputation: 437

django: how to make two models share one unique primary key

In my case, I have two models: Equipment and Asset, they both have their own fields but they should share one unique field: asset_number. By sharing, I mean that when creating a equipment, the asset_number user inputted would be check against both Equipment and Asset database. If it already exist in any, then there is going to be prompt telling the user that this is not unique.

For only one model, this is easily done by setting unique = True. However if I would like to do for two models, how should I proceed?

TIA

Upvotes: 0

Views: 792

Answers (2)

Matías Zanolli
Matías Zanolli

Reputation: 503

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):
    .
    .
    .

Upvotes: 0

Rob L
Rob L

Reputation: 3734

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.

Upvotes: 1

Related Questions