小编phi*_*her的帖子

Pydantic 在将数字分配给字符串时不进行验证

将不正确的属性分配给 Pydantic 模型字段时,不会发生验证错误。

from pydantic import BaseModel

class pyUser(BaseModel):
    username: str

    class Config:
        validate_all = True
        validate_assignment = True

person = pyUser(username=1234)
person.username
>>>1234
try_again = pyUser()

pydantic.error_wrappers.ValidationError:
[ErrorWrapper(exc=MissingError(), loc=('username',))]
<class '__main__.pyUser'>
Run Code Online (Sandbox Code Playgroud)

我怎样才能让 pydantic 验证作业?

python validation pydantic

7
推荐指数
1
解决办法
5093
查看次数

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

我正在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)

python django model exception

0
推荐指数
1
解决办法
344
查看次数

标签 统计

python ×2

django ×1

exception ×1

model ×1

pydantic ×1

validation ×1