0

I am creating a tracking app for projects where each project will have one or more groups. I want to add an alphanumeric string as the unique identifier (similar to the primary key) for groups. I know about UUID but it is a long string and I am looking for 10-15 characters long.

Could you please help me with how can I generate a unique string?

I want field "project_groupid" as a unique identifier.

Models.py

class project(models.Model):
    project_name = models.CharField(max_length=130,default="")
    project_customer = models.ForeignKey(customerOrganization, on_delete=models.CASCADE)

class project_target(models.Model):
    project = models.ForeignKey(project, on_delete=models.CASCADE)
    project_groupid = models.CharField(max_length=20,default="")
    group_name = models.CharField(max_length=100,default="")
    group_country = models.CharField(max_length=3,default="US")
    group_language = models.CharField(max_length=3,default="en")
Narendra Vishwakarma
  • 1,790
  • 2
  • 5
  • 7
  • "random.choice" doesn't guaranty for the uniqueness. Not sure if UUID4 will have unique numbers over the time. – Narendra Vishwakarma May 24 '20 at 10:59
  • I assume the OP has means of checking whether the newly generated random string hasn't been used previously (and repeating the process until a unique one is generated). – Błotosmętek May 24 '20 at 11:06
  • That's the way but wanted to see if we can generate unique ids without checking the database. – Narendra Vishwakarma May 24 '20 at 11:16
  • Welcome to the community! Could you please provide some sample code. This helps give context for others to answer your question. Often we see request for solutions whereas that might not be the right way to tackle your problem – idan May 24 '20 at 11:31
  • Sure, Code has been updated. I have added models.py where "project_groupid" should be alphanumeric unique identifier for each group. – Narendra Vishwakarma May 24 '20 at 11:55

1 Answers1

0

Django have a helper function for generating random strings get_random_string, it's usage is simple, pass the length and list of charters to use

from django.utils.crypto import get_random_string
get_random_string(10, 'abcdef0123456789')

However this method do not grant unique values, over time you may get the same random string, you should check against your database if the generated random identifier already exists

ahmed
  • 5,430
  • 1
  • 20
  • 36