make primary key with 2 fields in Django?
I want to make a primary key from 2 fields in Django.
Fields are below
- current Time
- userI开发者_开发百科d
How Can I do this??
Time + userid {PK } [ Current Time + userid]
Thank you!!
Most of the time, you don't actually need your multi-column key to be the primary key.
Django operates best with surrogate keys - that is, it automatically defines an autoincrement field called id
and sets that to be the primary key. That suits for almost all uses.
If you then need to enforce a unique constraint on your model across two or more fields, you can use the unique_together
setting in the inner Meta
class.
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.
If the key has to be single-column:
id is added "out-of-the-box" (variable.id) and for current time just add
from django.db import models
date = models.DateTimeField( auto_now_add=True)
in yourapp/models.py
so you have your 2 values, out of witch you can make your key in any shape you want.
if you want multi-column-key then read the other answer. Hope to help you.
精彩评论