Django 使用AutoLugfield填充现有模型对象

Django 使用AutoLugfield填充现有模型对象,django,django-extensions,Django,Django Extensions,我需要为已经存在的模型对象填充AutoLugfield。我的巴德意识到,slug字段非常方便和更好,以至于出于安全目的使用pk 数据库中已经有模型对象行。我想将AutoLugfield添加到它们中 任何人都知道我是如何做到这一点的 谢谢假设模型如下所示: class MyModel(...): title = <Charfield> slug = <AutoSlugField> def generate_another_slug(slug, cycle)

我需要为已经存在的模型对象填充AutoLugfield。我的巴德意识到,slug字段非常方便和更好,以至于出于安全目的使用pk

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

任何人都知道我是如何做到这一点的


谢谢

假设模型如下所示:

class MyModel(...):
    title = <Charfield>
    slug = <AutoSlugField>
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
生成另一个slug函数可以如下所示:

class MyModel(...):
    title = <Charfield>
    slug = <AutoSlugField>
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

因此,您希望基于不同的字段(如标题等)为所有模型对象生成一个slug?这是正确的@xyresI认为有条件地接受此答案。段塞必须是唯一的,因此必须正确处理碰撞。否则,感谢pointerI对其进行了测试,它不会处理并注意唯一性。我可以为我不想要的两个不同模型对象创建并保存相同的slug。编辑的答案以使用多个字段处理冲突或指示冲突,例如`slug\u text=model\u object.var1+。。。。try:model=model.objects.getslug=slug\u text除了DoesNotExist:modelobject.slug=slug\u text modelobject.save else look\u for\u anotjer\u slug'@unlockme我已经根据你的建议更新了答案。非常感谢。我还添加了另一个函数来生成新的slug,如果旧的slug不是唯一的。