V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fen
V2EX  ›  Python

Peewee 限制了 Field 中的 choices,为什么仍然可以插入其他数据?

  •  
  •   fen · 2013-05-28 21:29:48 +08:00 · 3037 次点击
    这是一个创建于 3956 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近看到 [Peewee](https://github.com/coleifer/peewee) 这个超简洁的 Python ORM,试着用了下,定义 User 模型:

    ```
    USER_ROLE = ('user', 'admin')

    class User(BaseModel):
    username = CharField()
    role = CharField(choices=USER_ROLE, default='user')
    ```

    创建表单后插入数据,注意这个 role 并不在我的 [choices](http://peewee.readthedocs.org/en/latest/peewee/models.html#field-initialization-arguments) 里

    ```
    k = User(username='admin', role='chairman')
    k.save()
    ```

    发现竟然插入成功了,可是我明明限制了 `choices` 啊,为什么会这样呢?
    2 条回复    1970-01-01 08:00:00 +08:00
    cute
        1
    cute  
       2013-05-29 07:57:15 +08:00
    看了代码,发现choices定义了,但是后面没有使用.
    楼主使用的应该是未完善的版本.
    我使用的是之前自己修改的.
    cute
        2
    cute  
       2013-05-29 08:09:55 +08:00   ❤️ 1
    其实可以这么声明一个就可以了.

    class ChoiceField(peewee.CharField):
    def db_value(self, value):
    return value if value in self.choices else self.default

    def python_value(self, value):
    return value if value in self.choices else self.default
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3424 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:14 · PVG 19:14 · LAX 04:14 · JFK 07:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.