我正在尝试添加一个slug字段,这是我在模型中尝试的内容,
slug = models.SlugField(unique=True)
def pre_save_receiver(sender, instance, *args, **kwargs):
slug = slugify(instance.title)
exists = Data.objects.filter(slug=slug).exists()
if not exists:
instance.slug = slug
else:
instance.slug = "%s-%s" % (slug, instance.id)
pre_save.connect(pre_save_receiver, sender=Data)
问题是,即使它是一个非常独特的标题,它也会在标题后面的slug字段中添加ID。 我该如何解决这个问题?谢谢你:)
答案 0 :(得分:0)
即使您正在更新已存在的实例,信号也始终预先保存。如果您正在更新,那么对slug的查询将返回一个现有实例:即您正在更新的实例。在这种情况下,您需要排除当前的那个。
query = Data.objects.filter(slug=slug)
if instance.pk:
query = query.exclude(pk=instance.pk)
if query.exists():
...
答案 1 :(得分:0)
模型至少具有以下内容:
class YourModel(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, null=True)
您需要在app文件夹中创建一个名为utils的文件,其中包含以下代码:
<强> utils.py 强>
from django.utils.text import slugify
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def unique_slug_generator(instance, new_slug=None):
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.title)
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = "{slug}-{randstr}".format(
slug=slug,
randstr=random_string_generator(size=4)
)
return unique_slug_generator(instance, new_slug=new_slug)
return slug
的 Models.py 强>
from django.db.models.signals import pre_save, post_save
from .utils import unique_slug_generator
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(pre_save_receiver, sender=YourModel)