简体   繁体   English

创建独特的slug django

[英]create unique slug django

I have a problem with creating unique slugs using django models. 我在使用Django模型创建唯一的子弹时遇到问题。 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. 如果已存在段,则应该有“段+ _1”,“段+ _2”等。同样,在创建新页面并且没有段的情况下,段应该是页面标题。 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. 您的代码中的三个问题。

  1. The first else means either self.id or self.slug is NOT blank. 第一else意味着要么self.idself.slug不是空白。 So if self.id is NOT blank and self.slug is blank, self.slug will not get a value. 因此,如果self.id不为空且self.slug为空,则self.slug将不会获得值。
  2. slug_exits == slug will always be False, because slug_exits is a Model object and slug is a string. slug_exits == slug始终为False,因为slug_exits是一个Model对象,而slug是一个字符串。 This is why you get the error! 这就是为什么您得到错误!
  3. You did a query in the loop, which may cause lots of hits to the DB. 您在循环中进行了查询,这可能会导致数据库遭受重大打击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM