20π
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.
- Django + Forms: Dynamic choices for ChoiceField
- Calculate point based on distance and direction
- How to unit test methods inside django's class based views?
- How do I convert kilometres to degrees in Geodjango/GEOS?
6π
Old question, but for anybody using Django 1.8+ the built in UUIDField could come in handy.
1π
Django has now included UUID Field in 1.8 and above.
A field for storing universally unique identifiers. Uses Pythonβs UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).
This field is generally used as a primary key and here is how you can use it with models ->
your_app/models.py
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# other fields
- How do you use Django-filter's '__in' lookup?
- Sometimes request.session.session_key is None
- Cross platform interface for virtualenv
0π
If I do a python manage.py inspectdb
the output is something like this:
class SomeModel(models.Model):
uid = models.TextField(primary_key=True)
class SomeOtherModel(models.Model):
uid = models.TextField()
This doesnβt work though. For whatever reason, this wonβt work if uid is the primary key. So I change it to this:
class SomeModel(models.Model):
uid = models.TextField()
class SomeOtherModel(models.Model):
somemodel = models.ForeignKey(SomeModel, db_column='uid', to_field='uid')
This seems to work, but is painfully slow.
- 'QuerySet' object has no attribute ERROR, trying to get related data on ManyToMany fields
- Is there a way to render a html page without view model?
- Converting a django ValuesQuerySet to a json object
-3π
For those who actually need to generate GUIDs:
guid = hashlib.sha1(str(random.random())).hexdigest()
- Can you declare multiple with variables in a django template?
- Python/Django: sending emails in the background