Login

Tag "id"

Snippet List

Username filled automatically with id

I thought this code for insert automatically id in username field. This method should be used in save method. This code work on a dbms that support transactions ( example: mysql+innodb or postgresql ). Let me know what you think about this snippet and if you advice an alternative solution by commenting below. Thanks :)

  • username
  • id
  • transaction
Read More

Friendly ID

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

  • field
  • id
Read More

Model with random ID

An abstract model base class that gives your models a random base-32 string ID. This can be useful in many ways. Requires a Django version recent enough to support model inheritance.

  • model
  • random
  • model-inheritance
  • id
  • primary-key
Read More

4 snippets posted so far.