实现UUID作为主键 [英] Implementing UUID as primary key
问题描述
我需要实现UUID作为主键,但我不知道如何在Django中执行。
I need to implement UUID as primary key but I'm not sure how to do it in Django.
我的代码
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)
推荐答案
self
意味着你需要传递一个实例。在你的情况下,你没有一个实例,这就是为什么你看到一个错误的参数的奇怪的错误。
self
means you need to pass in an instance. 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)
但是,这不是理想的解决方案。最好创建一个自定义数据库字段。由于这是一个常见的问题,所以有很多版本。我个人喜欢 david cramer的版本。
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.
这篇关于实现UUID作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!