使用 AutoSlugField 填充现有模型对象
Populate existing model objects with AutoSlugField
我需要为已经存在的模型对象填充一个 AutoslugField。我的坏人意识到 slug 字段比使用 pk 出于安全目的更方便和更好。
我的数据库中已有模型对象(行)。我想向它们添加 AutoSlugField。
任何人都知道我怎样才能做到这一点。
谢谢
假设模型如下所示:
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
我需要为已经存在的模型对象填充一个 AutoslugField。我的坏人意识到 slug 字段比使用 pk 出于安全目的更方便和更好。
我的数据库中已有模型对象(行)。我想向它们添加 AutoSlugField。
任何人都知道我怎样才能做到这一点。
谢谢
假设模型如下所示:
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