On Mon, Sep 6, 2010 at 7:19 AM, kmpm <[email protected]> wrote:
> I have a project running in a manufacturing industry that is actually
> built upon django.
> In this I need to generate a unique serial, batch or lot number
> (depending on what you would like to call it) that is a running number
> from 0 to whathever for each and every day.
> There is a high risk of concurrency so just finding the previous max
> and then do a +1 before saving is not what I want.
> The important part of the model looks like this...
>
> class ProducedEntity(models.Model):
> ....
> production_date = models.DateField(auto_now_add=True)
> lot_no = models.PositiveIntegerField(default=0)
>
> class Meta:
> unique_together = ('production_date', 'lot_no')
>
> Of course I could just save it and see if the .save() call works
> without generating a IntegrityError but that's not elegant.
> Is there a way of generating that number per day in a way that it's
> done when I save the model?
>
UUIDs are your best bet. Even if you generated 100 billion UUIDs a
second for the next 100 years, the chance of one collision would only
be 50% [1].
class ProducedEntity(models.Model):
....
uuid = models.CharField(max_length=36, unique=True)
def _hook_add_uuid(instance, sender, **kwargs):
import uuid
if not hasattr(instance, 'uuid') or not instance.uuid:
instance.uuid = str(uuid.uuid4())
from django.db.models.signals import pre_save
pre_save.connect(_hook_add_uuid, sender=ProducedEntity)
UUIDs can be stored more efficiently than that, its just a big 128 bit
number, so can be stored as 2 long integers. See your DB manual for
more info.
Cheers
Tom
[1]
http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.