创建独特的 slug django [英] create unique slug django
问题描述
我在使用 django 模型创建独特的 slug 时遇到问题.我想允许管理员用户从管理员的编辑页面更改 slug.当 slug 已经存在时,应该有slug + _1"、slug + _2"等.此外,当创建一个新页面并且没有 slug 时,slug 应该是页面标题.我有这个代码,但出于某种原因,管理员一直说带有这个 Slug 的页面已经存在".当我添加一个带有已经存在的 slug 的页面时.希望有人能帮助我
I have a problem with creating unique slugs using django models. I want to allow the admin user to change the slug from the edit page in the admin. When a slug already exists there should be "slug + _1", "slug + _2" etc. Also when a new page is created and there is no slug given the slug should be the page title. I have this code but for some reason the admin keeps saying "Page with this Slug already exists." when I add a page with a slug that already exists. Hope somebody can help me
def save(self, *args, **kwargs):
if not self.id and not self.slug:
self.slug = slugify(self.page_title)
else:
self.slug = slugify(self.slug)
slug_exists = True
counter = 1
slug = self.slug
while slug_exists:
try:
slug_exits = Page.objects.get(slug=slug)
if slug_exits == slug:
slug = self.slug + '_' + str(counter)
counter += 1
except:
self.slug = slug
break
super(Page, self).save(*args, **kwargs)
推荐答案
试试这个.自己没测试过.但它应该给你这个想法.
Try this. Didn't test it myself. But it should give you the idea.
import re
def save(self, *args, **kwargs):
if not self.id: # Create
if not self.slug: # slug is blank
self.slug = slugify(self.page_title)
else: # slug is not blank
self.slug = slugify(self.slug)
else: # Update
self.slug = slugify(self.slug)
qsSimilarName = Page.objects.filter(slug__startswith='self.slug')
if qsSimilarName.count() > 0:
seqs = []
for qs in qsSimilarName:
seq = re.findall(r'{0:s}_(\d+)'.format(self.slug), qs.slug)
if seq: seqs.append(int(seq[0]))
if seqs: self.slug = '{0:s}_{1:d}'.format(self.slug, max(seqs)+1)
super(Page, self).save(*args, **kwargs)
您的代码中存在三个问题.
Three problems in your code.
- 第一个
else
表示self.id
或self.slug
不为空.因此,如果self.id
不为空且self.slug
为空,self.slug
将不会获得值. slug_exits == slug
将始终为 False,因为slug_exits
是一个模型对象,而slug
是一个字符串.这就是您收到错误的原因!- 您在循环中执行了查询,这可能会导致对数据库的大量命中.
- The first
else
means eitherself.id
orself.slug
is NOT blank. So ifself.id
is NOT blank andself.slug
is blank,self.slug
will not get a value. slug_exits == slug
will always be False, becauseslug_exits
is a Model object andslug
is a string. This is why you get the error!- You did a query in the loop, which may cause lots of hits to the DB.
这篇关于创建独特的 slug django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!