Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing UUID as primary key

Tags:

uuid

django

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)
like image 922
André Avatar asked Feb 13 '13 12:02

André


2 Answers

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)
like image 198
Cesar Canassa Avatar answered Nov 13 '22 03:11

Cesar Canassa


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.

like image 37
Burhan Khalid Avatar answered Nov 13 '22 01:11

Burhan Khalid