'How to create short uuid with Django
I have a model and UUID as primary key field. UUID id is way too long. I'd like to have it short similar to YouTube.
class Video(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False,
)
Instead of this
UUID('b39596dd-10c9-42c9-91ee-9e45b78ce3c1')
I want to have just this
UUID('b39596dd')
How can I achieve above?
Solution 1:[1]
A bit old question, but shortuuidfield may be what you are looking for.
Solution 2:[2]
The first part of the uuid
is defined as the time_low
so we can do this, however it will no longer be a uuid.UUID
type.
sample = uuid.uuid4()
UUID('6af2fd74-fbaf-4a9a-a973-8d052634a624')
tl = sample.time_low
1794309492L
Then we just convert it back to hex,
hex(int(tl.time_low))[2:]
'6af2fd74'
You can do the same thing with just splitting it as a normal string but I don't see why it matters. Once you assign this to a variable it's a given so you can parse it as you choose.
Solution 3:[3]
You can use shortuuid library:
from shortuuid.django_fields import ShortUUIDField
id = ShortUUIDField(primary_key=True, length=11, max_length=11)
But you should pay attention to this issue. The smaller the size of the UUID, the higher the probability of Collision.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel Backman |
Solution 2 | gold_cy |
Solution 3 |