make primary key with 2 fields in Django?

后端 未结 3 880
别那么骄傲
别那么骄傲 2020-12-18 09:53

I want to make a primary key from 2 fields in Django.

Fields are below

- current Time 
- userId

How Can I do

3条回答
  •  伪装坚强ぢ
    2020-12-18 10:45

    It's not built into Django (see #373), but see the bottom of http://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys for the discussion. I've copied over the "alternative methods" section here for posterity.

    Alternative methods

    notnotpeter: Currently, you can "fake" it by declaring one of the keys to be primary in Django and adding a unique constraint to the model. (needs more info...examples?)

    mjm: This only works when there is a non-compound unique key to use, if I understand what's being proposed here. As such, it may be workable as a way to squeeze a design that naturally has CKs into Django, but it's of no use for working with an existing schema that has only the CK.

    djansoft: It can be done using unique-together.

    Tobu: You can't use just one key. A use case for illustration: a NamespacedTag? model with a CK made of a namespace and a name. The primary key can't be just the namespace or just the name since that would be ambiguous. The only solution (and I dislike it since it is bad modelling and forces database accesses to be serialized on a counter) is to use an AutoField?.

    toszter: Call me nutty, but why not declare any number of columns as primary key in your model, which django then uses to create a "hidden" pk_composite column that's just a hash of the three pk values in the row? When you do a lookup on a pk, you assume the ENTIRE combination of values is the primary key, nothing more or less. So when you look up according to the values needed to create the full pk_composite, the hash always computes and if the hash algorithm is public, can be used off the URL, the querystring in db lookups, and just about anywhere. Seems pretty simple in my mind but then again I am not going into great detail here.

    That being said, I would create an ID on the table and make that the primary key. Then add a unique contraint on the user_id + timestamp.

提交回复
热议问题