Last active
April 6, 2017 23:06
-
-
Save archatas/a9f312cc492ca2085bf3937275ec444b to your computer and use it in GitHub Desktop.
Random unique string ID mixin for Django models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: UTF-8 -*- | |
from __future__ import unicode_literals | |
import shortuuid | |
from django.conf import settings | |
from django.db import models | |
from django.utils.translation import ugettext_lazy as _ | |
RANDOM_UNIQUE_ID_LENGTH = getattr(settings, "RANDOM_UNIQUE_ID_LENGTH", 12) | |
def get_new_id(): | |
return shortuuid.ShortUUID().random(length=RANDOM_UNIQUE_ID_LENGTH) | |
class RandomUniqueIdMixin(models.Model): | |
id = models.CharField( | |
_("ID"), | |
primary_key=True, | |
db_index=True, | |
max_length=RANDOM_UNIQUE_ID_LENGTH, | |
default=get_new_id, | |
) | |
class Meta: | |
abstract = True | |
def save(self, *args, **kwargs): | |
if self._state.adding: | |
# ensure that the id is unique | |
while self.__class__.objects.filter(id=self.id).exists(): | |
self.id = get_new_id() | |
# finally save the object | |
super(RandomUniqueIdMixin, self).save(*args, **kwargs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: UTF-8 -*- | |
""" | |
To use the RandomUniqueIdMixin mixin, extend it instead of models.Model | |
""" | |
from __future__ import unicode_literals | |
from django.db import models | |
from django.utils.translation import ugettext_lazy as _ | |
from .base import RandomUniqueIdMixin | |
class Message(RandomUniqueIdMixin): | |
# ...fields and methods here... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shortuuid==0.5.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment