2013-06-04 13 views
23

モデルフィールドからdjangoで要求ごとに異なる/固有のIDを生成したいとします。私はこれをしましたが、私は同じIDを得続けます。モデルフィールドからdjangoで一意のIDを生成

class Paid(models.Model): 
    user=models.ForeignKey(User) 
    eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True, default=uuid.uuid4()) #want to generate new unique id from this field 

    def __unicode__(self): 
     return self.user 

答えて

35

UPDATE:あなたがDjangoの1.8またはより優れたを使用している場合は、@madzohanは、以下の正しい答えを持っています。


はこのようにそれを実行します。

#note the uuid without parenthesis 
eyw_transactionref=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4) 

括弧であなたはの機能を評価するためのモデルがにインポートされると、これはすべてのために使用されるUUIDをもたらすであろう理由インスタンスが作成されました。

括弧なしでは、フィールドにデフォルト値を与えるために呼び出す必要がある関数だけを渡し、モデルをインポートするたびに呼び出されます。

また、このアプローチを取ることができます:

class Paid(models.Model): 
    user=models.ForeignKey(User) 
    eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True) 

    def __init__(self): 
     super(Paid, self).__init__() 
     self.eyw_transactionref = str(uuid.uuid4()) 

    def __unicode__(self): 
     return self.user 

は、この情報がお役に立てば幸い!

+0

、それは保存していないことを意味します!私は私の意見を投稿する必要がありますか? – picomon

+1

デフォルト値がある場合、フィールド定義に 'null = True'は必要ありません。私は答えから削除します。それなしで試してみてください。 –

+0

このエラーが発生しました。IntegrityError at/pay/ (1048、 "列 'eyw_transactionref'はnullにはできません)空白も削除しました。 – picomon

58

バージョン1.8 DjangoはUUIDField https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.UUIDField

import uuid 
from django.db import models 

class MyUUIDModel(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 
    # other fields 
+8

あなたがDjango1.8 +を持っている場合これは実際の答えです: –

+0

'unique = True'も必要ですか? – Sevenearths

+0

@Sevenearths http://stackoverflow.com/questions/31499836/does-djangos-new-uuidfields-default-attribute-take-care-of-the-uniqueness – madzohan

8

を持っているので、あなたが必要かというDjangoのUUIDフィールドよりもカスタムID生成機能を使用する場合は、save()方法でwhileループを使用することができます。十分に大きな固有のIDについては、これ以上、単一のDBコール一意性を検証するためになることはほとんどないだろう:私はthat..I'mは今、私のデシベルにNULLなった

urlhash = models.CharField(max_length=6, null=True, blank=True, unique=True) 

# Sample of an ID generator - could be any string/number generator 
# For a 6-char field, this one yields 2.1 billion unique IDs 
def id_generator(size=6, chars=string.ascii_uppercase + string.digits): 
    return ''.join(random.choice(chars) for _ in range(size)) 

def save(self): 
    if not self.urlhash: 
     # Generate ID once, then check the db. If exists, keep trying. 
     self.urlhash = id_generator() 
     while MyModel.objects.filter(urlhash=self.urlhash).exists(): 
      self.urlhash = id_generator() 
    super(MyModel, self).save() 
関連する問題