So when every day ticks over at midnight, the serial number starts at
zero again? Does production continue across the time 00:00? Why don't
you use a continuously increment number?
I don't know what the "right" thing to do is. I'm sure there will be a
classic solution. I think I would be writing a singleton function
nextnum() which returns the next number as required and then
lot_no = models.IntegerField(default=nextnum)
I'm not sure what would happen threadwise but a singleton would be a
natural place to deal with thread-locking and restarting the sequence
when the clock ticks over.
lot_no then gets the value prior to the save()
Mike
Then it would need to be a database trigger. At least in PostgreSQL you
could write it in the Python proc language supplied. It could create a
new temporary table with an incrementing column each night as a source
for the sequence number. That would cover occasional system stoppages
during the day.
I'm not sure how to integrate that in a nice way with django models
except as you alreadhy indicated with unique for date.
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
I would go with the simplest solution and keep an eye on performance as
it scales. Gives you plenty of time to research plan B.
That'll be 2c please
M
--
Shamail Tayyab
Blog: http://shamail.in/blog
I can't see if you mentioned which database you are using, but if you
are using Postgres, why can't you just use the default PK field and run
a cronjob to excecute a postgres SETVAL at midnight?
#!/bin/sh
DATECODE=$( date +%Y%m%d )
echo "SET SETVAL('table_id_seq', '${DATECODE}0000');" | psql ....
Regards
Darryl