django - 使用 AutoSlugField 填充现有模型对象

标签 django django-extensions

我需要为已经存在的模型对象填充 AutoslugField。我的错误意识到 slug 字段非常方便,而且比使用 pk 用于安全目的更好。

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

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

谢谢

最佳答案

假设模型如下所示:

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

你可以写一个 for循环读取 MyModel 中的所有对象并使用 django.utils.text.slugify 转换 title成蛞蝓。您可以在 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

关于django - 使用 AutoSlugField 填充现有模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49339364/

相关文章:

django - 更改 Django 开发服务器输出日志文本的颜色

python - 如何在多对多字段中自定义 django admin 搜索结果

python - shell_plus 安装 Django 时出现错误 - ImportError : cannot import name 'Type

django - 使用 django-extensions 插件在 jupyter 笔记本中打印 sql 查询

python - 如何复制 Django 模型实例和所有相关数据

python - Django 主题/皮肤存储库

jquery - 如何保护ajax在没有登录的情况下被使用?

python - 在 Django 运行脚本中传递命令行参数

ipython-notebook - 通过django_extensions设置IPython Notebook保存目录

python - 如何使用 SHELL_PLUS_DONT_LOAD? django-extensions==1.6.1, Django==1.9.2