Skip to content

Commit

Permalink
feat: Add prefix and max_length to the Django field
Browse files Browse the repository at this point in the history
  • Loading branch information
skorokithakis committed Nov 8, 2021
1 parent c006597 commit 3cd2dba
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Changelog


## Unreleased
## v1.0.6 (2021-11-08)

### Fixes

Expand Down
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,21 @@ from shortuuid.django_fields import ShortUUIDField

class MyModel(models.Model):
# A primary key ID of length 16 and a short alphabet.
id = ShortUUIDField(length=16, alphabet="abcdefg1234", primary_key=True)
id = ShortUUIDField(
length=16,
max_length=40,
prefix="id_",
alphabet="abcdefg1234",
primary_key=True,
)

# A short UUID of length 22 and the default alphabet.
api_key = ShortUUIDField()
```

The field is the same as the `CharField`, with `max_length` replaced with `length`, an
`alphabet` argument added and the `default` argument removed. Everything else is exactly
the same, e.g. `index`, `help_text`, etc.
The field is the same as the `CharField`, with a `length` argument (the length of the
ID), an `alphabet` argument, and the `default` argument removed. Everything else is
exactly the same, e.g. `index`, `help_text`, `max_length`, etc.


Compatibility note
Expand Down
15 changes: 12 additions & 3 deletions shortuuid/django_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,28 @@ class ShortUUIDField(models.CharField):
description = _("A short UUID field.")

def __init__(self, *args, **kwargs):
self.length = kwargs["max_length"] = kwargs.pop("length", 22)
self.length = kwargs.pop("length", 22)
self.prefix = kwargs.pop("prefix", "")

if "max_length" not in kwargs:
# If `max_length` was not specified, set it here.
kwargs["max_length"] = self.length

self.alphabet = kwargs.pop("alphabet", None)
kwargs["default"] = self._generate_uuid

super().__init__(*args, **kwargs)

def _generate_uuid(self):
"""Generate a short random string."""
return ShortUUID(alphabet=self.alphabet).random(length=self.length)
return self.prefix + ShortUUID(alphabet=self.alphabet).random(
length=self.length
)

def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
kwargs["alphabet"] = self.alphabet
kwargs["length"] = kwargs.pop("max_length")
kwargs["length"] = self.length
kwargs["prefix"] = self.prefix
kwargs.pop("default", None)
return name, path, args, kwargs

0 comments on commit 3cd2dba

Please sign in to comment.