Abishek
Abishek

Reputation: 369

django uuid or hashid field for primary keys? and how to prefix the generated ids with say "cust_"

I am currently using django-shortuuidfield to generate a unique UUID primary key on the Customer model as shown below

class Customer(models.Model):
    customer_id = ShortUUIDField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255, blank=False)

This guarantees that the customer_id field is unique with space and time. However, this generates an id similar to B9fcKdMDHbwKCBoADjbNyA and I want to prefix this with cust_ to make it like this cust_B9fcKdMDHbwKCBoADjbNyA. How do I achieve this without making multiple db calls?

I also looked into django-hashid-field which supports prefixes out of the box but this does not guarantee UUID, and on a larger scale, we may run into unique contain failed issues that are not desirable.

Any thoughts on this? Let me know...

Upvotes: 0

Views: 1534

Answers (1)

Nick
Nick

Reputation: 26

Probably a stale thread, but I just recently came across this problem myself. I ended up just forking and modifying ShortUUIDField module to include a prefix and suffix optionally. Kind of a hacky job I have to admit, but I thought I'd share for posterity.

https://github.com/nick-fournier/django-customshortuuidfield

use like:

class Business(models.Model):
     id = CustomShortUUIDField(primary_key=True, prefix="biz_")

Upvotes: 1

Related Questions