Search code examples
sqldjangoschemahashtablecomposite-primary-key

Creating a hashed Primary Key when composite key is not permitted


My question is about the solution seen in the post below... I think that is is a fantastic idea. Especially since Django has had the composite primary key issue for years. To me this is a great workaround given that you know the items in advance. However, this seems to have little feedback given that so many people have looked into composite keys in django. Can someone please point out the downside to this approach?

I feel that as long as the salesperson has a unique ID you shouldn't have any hash collisions correct? even if the years overlap. Additionally as long as you provide an index on the salesperson column you can perform fast select statements as this simulates the index automatically placed on a primary key.

However, I am clearly only seeing the positive, is there a danger with using this approach.

Thank you for any info.

Composite primary key, Google app engine (django)


Solution

  • Storing a hash of two columns as the primary key is not very readable. You could consider an alternative. For example, for salesman and year, you could use the name of the salesman, then underscore, then year as the primary key:

    ID         Salesman    Year    ...
    Joe_2011   Joe         2011    ...
    

    This is a lot easier to debug than storing a hash.

    However, the hash is a perfectly safe and common technique, if that is what you prefer.