如果它已经存在于数据库中,如何将索引添加到我的 slug?

How to add index to my slug if it already exists in database?

当我创建新的 post 之后我需要做的是:

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()

A pre-save signal 是处理此问题的最佳方法。每次一个实例即将被保存时,都会触发信号和 运行 一些逻辑。在这种情况下,它将在保存之前填充 slug 字段。

from django.db.models.signals import pre_save
from django.dispatch import receiver

# you other stuff goes here

@receiver(pre_save, sender=MyModel)
def set_slug(sender, instance, *args, **kwargs):
    instance.slug = slugify(instance.title)

就是这样!

如果您的信号未连接应用程序,您可以将其放在 models.py 上。但是如果你用它来连接不同的应用程序,或者一个共同的信号到多个应用程序,你应该有一个单独的文件来放置。

请注意:看到那个 sender=MyModel 片了吗?那就是将信号绑定到特定模型。如果您有很多模型会使用 slug,您可以将其删除以使预保存挂钩可用于多个模型。