当我创建新帖子时,我需要执行以下操作:
1. Generate slug from self.title with slugify
2. Check if this slug does not exists we save post with self.slug
3. If this slug already exists we save post with self.slug + '-' + count index
我找到了可行的解决方案,但我是 django 的新手,所以我想问你这是最佳解决方案吗?
#models.py
from django.db import models
from django.shortcuts import reverse
from django.utils.text import slugify
from django.db.models.signals import post_save
from django.dispatch import receiver
class Post(models.Model):
title = models.CharField(max_length=150, db_index=True)
slug = models.SlugField(max_length=150, blank=True, unique=True)
def get_absolute_url(self):
return reverse('post_detail_url', kwargs={'slug': self.slug})
@receiver(post_save, sender=Post)
def set_slug(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = slugify(instance.title)
while Post.objects.filter(slug__startswith=instance.slug).exists():
instance.slug += '-' + str(Post.objects.filter(slug__startswith=instance.slug).count())
instance.save()