Sunday, May 30, 2010

Model super class with overriding save method

Hi,

because of hysterical raisins I need that the models of a simple app I
was tasked upon have their primary fields to consist of strings of
randomly generated characters (think something like
'876nce8yr85yndxw45') of a given length. I'm trying to create a super
class that provides this facility, so that the actual models derive
from it. I came up with

class CustomModel(models.Model):
id = models.CharField(max_length=12 primary_key=True)

class Meta:
abstract = True

def save(self, force_insert=False, force_update=False):
if not self.id:
try:
while True:
id = random_identifier()
self.__class__.objects.get(pk=id)
except self.__class__.DoesNotExist:
self.id = id
models.Model.save(self, force_insert, force_update)

apart for a window of collisions on clusters, is there a better way to
accomplish this? Ideas?

Thanks a lot,
Amit.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment