Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have models.UUIDField field without dash

Tags:

python

django

I tried to have models.UUIDField without dash, by using default=uuid.uuid4().hex (Instead of default=uuid.uuid4())

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    api_key = models.UUIDField(default=uuid.uuid4().hex, editable=False, unique=True)
    subscription = models.IntegerField(
        choices=[(s.value, s.name) for s in Subscription],
        null=False,
        blank=False
    )

    def __str__(self):
        return str(self.api_key)

However, the resultant result still come with dash.

django=# select * from users_profile;
 id |               api_key                | secret_key | subscription | user_id
----+--------------------------------------+------------+--------------+---------
  1 | 9da3546c-660c-46c6-adc4-6a13e6ee202b |            |            0 |       1
  2 | 9cbc3a68-7f50-4b18-9e61-7b009f22a0e8 |            |            0 |       2
(2 rows)

May I know how to have models.UUIDField field without dash?. I would like to store in database without dashes, and use it without dashes.

like image 555
Cheok Yan Cheng Avatar asked Aug 24 '18 13:08

Cheok Yan Cheng


2 Answers

Are you using PostgreSQL by any chance? The UUIDField may be using the native uuid type for the column. It stores it efficiently using only 16 bytes (without dashes). If that is the case, it is not storing the dashes, only showing them when you select.

The good news is that in Python code you are getting a UUID object, so you can do self.api_key.hex to get a string without dashes.

like image 62
user10269945 Avatar answered Nov 04 '22 17:11

user10269945


Use CharField field instead of UUIDField,

def generate_uuid():
    return uuid.uuid4().hex


class Profile(models.Model):
    api_key = models.CharField(default=generate_uuid, editable=False, unique=True, max_length=40)
like image 24
JPG Avatar answered Nov 04 '22 16:11

JPG