base setup
This commit is contained in:
32
at_django_boilerplate/utils/mixins.py
Executable file
32
at_django_boilerplate/utils/mixins.py
Executable file
@@ -0,0 +1,32 @@
|
||||
# mixins.py
|
||||
from django.db import models
|
||||
from at_django_boilerplate.utils.hash_utils import encode_id
|
||||
import uuid
|
||||
|
||||
|
||||
class UUIDMixin(models.Model):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
class HashidSlugMixin(models.Model):
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
slug = models.SlugField(max_length=10, unique=True,null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
# is_new = self.pk is None
|
||||
is_new = True
|
||||
super().save(*args, **kwargs)
|
||||
if is_new and not self.slug:
|
||||
self.slug = encode_id(self.pk)
|
||||
super().save(update_fields=['slug'])
|
||||
|
||||
def generate_slug(self):
|
||||
if not self.slug:
|
||||
self.slug = encode_id(self.pk)
|
||||
self.save(update_fields=['slug'])
|
||||
return self.slug
|
||||
Reference in New Issue
Block a user