- Author:
- agusmakmun
- Posted:
- February 17, 2018
- Language:
- Python
- Version:
- Not specified
- Score:
- 1 (after 1 ratings)
Generate unique slug refference by another field.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | from django.utils.text import slugify
def generate_unique_slug(klass, field, instance=None):
"""
return unique slug if origin slug is exist.
eg: `foo-bar` => `foo-bar-1`
:param `klass` is Class model.
:param `field` is specific field for title.
:param `instance` is instance object for excluding specific object.
"""
origin_slug = slugify(field)
unique_slug = origin_slug
numb = 1
if instance is not None:
while klass.objects.filter(slug=unique_slug).exclude(id=instance.id).exists():
unique_slug = '%s-%d' % (origin_slug, numb)
numb += 1
else:
while klass.objects.filter(slug=unique_slug).exists():
unique_slug = '%s-%d' % (origin_slug, numb)
numb += 1
return unique_slug
"""
# USAGE EXAMPLE
from django.db import models
from django.contrib.auth.models import User
from myapp.utils import generate_unique_slug
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
def save(self, *args, **kwargs):
if self.slug: # edit
if slugify(self.title) != self.slug:
self.slug = generate_unique_slug(Post, self.title)
else: # create
self.slug = generate_unique_slug(Post, self.title)
super(Post, self).save(*args, **kwargs)
"""
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.