4

我需要为已经存在的模型对象填充 AutoslugField。我的坏人意识到 slug 字段是如此方便和更好,以至于将 pk 用于安全目的。

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

任何人都知道我怎么能做到这一点。

谢谢

4

1 回答 1

5

假设模型如下所示:

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

您可以编写一个for循环来读取所有对象MyModel并用于django.utils.text.slugify转换title为 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
于 2018-03-17T17:57:54.453 回答