Задать вопрос

Тел: +7 965 3737 888





Friendly ID

<p>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.</p>
<p>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).</p>
<p>To use it:
    import friendly_id</p>
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)
        super(MyModel, self).save(*args, **kwargs)

    if self.id and not self.invoice_id

<p>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:</p>
obj.id   obj.invoice_id
1        TTH9R
2        45FLU
3        6ACXD
4        8G98W
5        AQ6HF
6        DV3TY
9999999  J8UE5

<p>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 :-) </p>
<p>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 :-)</p>

Вопрос полезен? Да0/Нет0