[英]Implementing UUID as primary key
I need to implement UUID as primary key but I'm not sure how to do it in Django. 我需要将UUID作为主键实现,但我不确定如何在Django中执行它。
My code 我的代码
class LinkRenewAd(models.Model): # This model will generate the uuid for the ad renew link
def make_uuid(self):
return str(uuid.uuid1().int>>64)
uuid = models.CharField(max_length=36, primary_key=True, default=make_uuid, editable=False)
main = models.ForeignKey(Main)
expiration_date = models.DateTimeField()
date_inserted = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)
When I try to generate this new model on South I got the error: 当我尝试在南方生成这个新模型时,我得到了错误:
TypeError: make_uuid() takes exactly 1 argument (0 given)
Django 1.8 comes with a built-in UUID field Django 1.8带有内置的UUID字段
Example: 例:
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
self
means you need to pass in an instance. self
意味着你需要传入一个实例。 In your case, you don't have an instance, which is why you are seeing the strange error of a missing argument. 在您的情况下,您没有实例,这就是您看到缺少参数的奇怪错误的原因。
To solve your problem, move the method that generates the field of out of your model class: 要解决您的问题,请移动生成模型类之外的字段的方法:
def make_uuid():
return str(uuid.uuid1().int>>64)
class Foo(models.Model):
id = models.CharField(max_length=36, primary_key=True, default=make_uuid)
However, this is not the ideal solution. 但是,这不是理想的解决方案。 It is better to create a custom database field. 最好创建一个自定义数据库字段。 As this is a common problem, there are many versions out there. 由于这是一个常见问题,因此有很多版本。 I personally like david cramer's version . 我个人喜欢大卫克莱默的版本 。
You are passing the function around, which will be called up somewhere down in models.Charfield
, instead from some object of LinkRenewAd
, so no instance of any object ( self
) is passed to this method , which actually expects one. 你是绕过功能,这将被调用在某处models.Charfield
,而不是从某些对象LinkRenewAd
,所以没有任何对象(实例self
)传递给这个方法,这实际上期望之一。 So, instead, make it a static function , or a lambda function, or define it as a non-member of the class. 因此,相反,使其成为静态函数或lambda函数,或将其定义为类的非成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.