gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:00:52 25 4
gpt4 key购买 nike

我需要为已经存在的模型对象填充 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com