Is there any way to use GUIDs in django?
I'd create a basic GUID Model in order to reuse it's properties for any other models in my projects. Model inheritance is working nicely since several versions prior to Django 1.0 and is quite stable with Django 1.0.
Create something like project/common/models.py and place there this class:
import hashlib
import random
from django.db import models
class GUIDModel(models.Model):
guid = models.CharField(primary_key=True, max_length=40)
def save(self, *args, **kwargs):
if not self.guid:
self.guid = hashlib.sha1(str(random.random())).hexdigest()
super(GUIDModel, self).save(*args, **kwargs)
Then create your other models as usual:
from common.models import GUIDModel
class Customer(GUIDModel):
name = models.CharField(max_length=64)
class Product(GUIDModel):
name = models.CharField(max_length=64)
class Sale(GUIDModel):
customer = models.ForeignKey(Customer)
product = models.ForeignKey(Product)
items = models.PositiveIntegerField()
And everything should work nicely with GUIDs as primary keys instead of autoincremental integers.
Old question, but for anybody using Django 1.8+ the built in UUIDField could come in handy.
Take a look at Django-extensions UUID Field