问题
I need to implement UUID as primary key but I'm not sure how to do it in 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)
回答1:
Django 1.8 comes with a built-in UUID field
Example:
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
回答2:
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)
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.
回答3:
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. So, instead, make it a static function, or a lambda function, or define it as a non-member of the class.
来源:https://stackoverflow.com/questions/14853728/implementing-uuid-as-primary-key