使用AutoSlugField

时间:2018-03-17 16:43:29

标签: django django-extensions

我需要为已有的模型对象填充AutoslugField。我的不好意识到slug字段非常方便,并且更好地使用pk用于安全目的。

我已经在数据库中有模型对象(行)。我想向他们添加AutoSlugField。

任何人都知道如何实现这一目标。

由于

1 个答案:

答案 0 :(得分:0)

假设模型如下所示:

class MyModel(...):
    title = <Charfield>
    slug = <AutoSlugField>

您可以编写for循环来阅读MyModel中的所有对象,并使用django.utils.text.slugifytitle转换为slug。你可以在shell中运行它:

from django.utils.text import slugify

from myapp.models import MyModel


# The for loop to create new slugs and update db records

for obj in MyModel.objects.all():
    if not obj.slug: # only create slug if empty

        slug = slugify(obj.title)

        cycle = 1 # the current loop cycle

        while True:
            # this loop will run until the slug is unique
            try:
                model = MyModel.objects.get(slug=slug_text)
            except MyModel.DoesNotExist:
                obj.slug = slug
                obj.save()
                break
            else:
                slug = generate_another_slug(slug, cycle)

            cycle += 1 # update cycle number

generate_another_slug函数可能如下所示:

def generate_another_slug(slug, cycle):
    """A function that takes a slug and 
    appends a number to the slug

    Examle: 
        slug = 'hello-word', cycle = 1
        will return 'hello-word-1'
    """
    if cycle == 1:
        # this means that the loop is running 
        # first time and the slug is "fresh"
        # so append a number in the slug
        new_slug = "%s-%s" % (slug, cycle)
    else:
        # the loop is running more than 1 time
        # so the slug isn't fresh as it already 
        # has a number appended to it
        # so, replace that number with the 
        # current cycle number
        original_slug = "-".join(slug.split("-")[:-1])
        new_slug = "%s-%s" % (original_slug, cycle)

    return new_slug
相关问题