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

时间:2019-04-18 11:59:26

标签: python django exception model

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

在脚本顶部,我有这个:

import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE','versal.settings')
import django
django.setup()

我正在尝试处理完整性错误-我的子弹必须是唯一的,所以当一个不是唯一的时,我想通过在子弹上添加'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

运行此代码时,我得到了:

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

1 个答案:

答案 0 :(得分:4)

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

from django.db import IntegrityError