1

我弄乱了一些代码,并遇到了一个特殊的问题:

def find_available_slug(object, instance, slug)
    try:
        sender_node = object.objects.get(slug=slug)
    except object.DoesNotExist:
        instance.slug = slug
    else:
        slug = '%s_' % slug
        find_available_slug(object, instance, slug)
    return

我遇到的问题是有时会objects.get(slug=slug)引发MultipleObjectsReturned异常,因为该字段在我的数据库中不是唯一的。我想知道如何MultipleObjectsReturned在“else”语句仍会被执行的情况下干净地捕捉到。

4

2 回答 2

2

或者,根本不要使用该else子句:

def find_available_slug(object, instance, slug)
    try:
        sender_node = object.objects.get(slug=slug)
    except object.DoesNotExist:
        instance.slug = slug
        return
    except object.MultipleObjectsReturned:
        pass

    slug = '%s_' % slug
    find_available_slug(object, instance, slug)
于 2012-09-27T02:46:15.700 回答
2

简单的解决方案:诀窍是在调用方法时捕获MultipleObjectsReturned第二try条语句。get这样,不会引发异常并且继续正常执行。

作品:

def find_available_slug(object, instance, slug)
    try:
        try:
            sender_node = object.objects.get(slug=slug)
        except object.MultipleObjectsReturned:
            pass
    except object.DoesNotExist:
        instance.slug = slug
    else:
        slug = '%s_' % slug
        find_available_slug(object, instance, slug)
    return

不工作:

def find_available_slug(object, instance, slug)
    try:
        sender_node = object.objects.get(slug=slug)
    except object.MultipleObjectsReturned:
        pass
    except object.DoesNotExist:
        instance.slug = slug
    else:
        slug = '%s_' % slug
        find_available_slug(object, instance, slug)
    return

第二种“幼稚”方法不起作用的原因是,如果捕获到异常,解释器将不会遍历该else:子句。反而会默默无闻return

于 2012-09-26T20:45:08.893 回答