This is just modified version of friendly id for make this script compatible with python 3.x
Invoice numbers like "0000004" are a little unprofessional in that they expose how many sales a system has made, and can be used to monitor the rate of sales over a given time. They are also harder for customers to read back to you, especially if they are 10 digits long.
This is simply a perfect hash function to convert an integer (from eg an ID AutoField) to a unique number. The ID is then made shorter and more user-friendly by converting to a string of letters and numbers that wont be confused for one another (in speech or text).
import friendly_id
class MyModel(models.Model): invoice_id = models.CharField(max_length=6, null=True, blank=True, unique=True)
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **kwargs)
# Populate the invoice_id if it is missing
if self.id and not self.invoice_id:
self.invoice_id = friendly_id.encode(self.id)
self.save()
if self.id and not self.invoice_id
When an object from this model is saved, an invoice ID will be generated that does not resemble those surrounding it. For example, where you are expecting millions of invoices the IDs generated from the AutoField primary key will be:
obj.id obj.invoice_id
1 TTH9R
2 45FLU
3 6ACXD
4 8G98W
5 AQ6HF
6 DV3TY
...
9999999 J8UE5
The functions are deterministic, so running it again sometime will give the same result, and generated strings are unique for the given range (the default max is 10,000,000). Specifying a higher range allows you to have more IDs, but all the strings will then be longer. You have to decide which you need: short strings or many strings :-)
This problem could have also been solved using a random invoice_id generator, but that might cause collisions which cost time to rectify, especially when a decent proportion of the available values are taken (eg 10%). Anyhow, someone else has now already written this little module for you, so now you don't have to write your own :-)