名称'IntegrityError'未定义-为什么不能在此脚本上使用'except:IntegrityError'?

phi*_*her 0 python django model exception

我正在django应用程序内部的app_name文件夹的根目录中运行脚本;如在app_name> app_name中。

在脚本的顶部,我有这个:

import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE','versal.settings')
import django
django.setup()
Run Code Online (Sandbox Code Playgroud)

我正在尝试处理完整性错误-我的子弹必须是唯一的,所以当一个不是唯一的时,我想通过向子弹添加1来处理完整性错误。

        try:
            podcast_instance.slug = slugify(parsed_podcast.title)
            podcast_instance.save()
            podcast_saves += 1
        except IntegrityError:
            podcast_instance.slug = slugify(parsed_podcast.title + '1')
            podcast_instance.save()
            podcast_saves += 1
Run Code Online (Sandbox Code Playgroud)

当我运行这段代码时,我得到了:

Traceback (most recent call last):
  File "podcasts.py", line 166, in <module>
    podcasty()
  File "podcasts.py", line 159, in podcasty
    submit(podcast_objects,podcast_rss)
  File "podcasts.py", line 73, in submit
    except IntegrityError as e:
NameError: name 'IntegrityError' is not defined
Run Code Online (Sandbox Code Playgroud)

gde*_*ef_ 6

您需要先导入它,然后再使用它。

from django.db import IntegrityError
Run Code Online (Sandbox Code Playgroud)