推荐学习书目
› 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 · May 28, 2013 · 3920 views
    This topic created in 4870 days ago, the information mentioned may be changed or developed.
    最近看到 [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 replies  •  1970-01-01 08:00:00 +08:00
    cute
        1
    cute  
       May 29, 2013
    看了代码,发现choices定义了,但是后面没有使用.
    楼主使用的应该是未完善的版本.
    我使用的是之前自己修改的.
    cute
        2
    cute  
       May 29, 2013   ❤️ 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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3631 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 488ms · UTC 00:54 · PVG 08:54 · LAX 17:54 · JFK 20:54
    ♥ Do have faith in what you're doing.