André
André

Reputation: 25584

Implementing UUID as primary key

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)

Upvotes: 15

Views: 6928

Answers (3)

Cesar Canassa
Cesar Canassa

Reputation: 20243

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)

Upvotes: 13

Burhan Khalid
Burhan Khalid

Reputation: 174718

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.

Upvotes: 8

nims
nims

Reputation: 3881

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.

Upvotes: -1

Related Questions