Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42758

How to have models.UUIDField field without dash

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.

Upvotes: 12

Views: 17908

Answers (2)

user10269945
user10269945

Reputation: 186

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.

Upvotes: 17

JPG
JPG

Reputation: 88589

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)

Upvotes: 8

Related Questions