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
sugarkeek
V2EX  ›  Python

Flask Admin 生成的模型视图,在创建后提交时主键为空

  •  
  •   sugarkeek · 2019-11-15 06:38:27 +08:00 · 3068 次点击
    这是一个创建于 1617 天前的主题,其中的信息可能已经有所发展或是发生改变。

    模型代码:

    class Problems(db.Model):
    
        __tablename__ = 'problems'
    
        id = db.Column(db.String(45), primary_key=True)
    
        ......
    
        def __init__(self):
    
            self.id = str(uuid4())
    

    用的是 Flask Admin 默认生成的模型视图,创建后提交报错

    sqlalchemy.orm.exc.FlushError: Instance <Problems at 0x7e3b050> has a NULL identity key.  If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values.  Ensure also that this flush() is not occurring at an inappropriate time, such as within a load() event.
    
    1. 这主键他默认也不显示,在构造函数里生成他也不调用。这个是 Flask Admin 需要设置的地方,还是因为我的代码有问题?

    目前我只能加上默认自动生成,不知道有没有更好的办法,或者说问题的关键在哪里?

    id = db.Column(db.String(45), primary_key=True, default=str(uuid4()))
    
    9 条回复    2020-06-11 19:11:56 +08:00
    cz5424
        1
    cz5424  
       2019-11-15 08:10:19 +08:00 via iPhone
    9102 年用前后端分离吧,这个很不好用是真的
    jry
        2
    jry  
       2019-11-15 08:37:06 +08:00 via iPhone
    同意 1 楼
    mianbao1
        3
    mianbao1  
       2019-11-15 08:43:52 +08:00 via iPhone
    同意 2 楼
    sugarkeek
        4
    sugarkeek  
    OP
       2019-11-15 08:49:38 +08:00
    @cz5424 #1 我有前后端分离的...... 我前端前后端分离,后台用 flask-admin
    Latin
        5
    Latin  
       2019-11-15 09:02:32 +08:00
    重写 database 基类 CRUD 都写上,继承下就 OK 了
    encro
        6
    encro  
       2019-11-15 09:03:24 +08:00
    id = db.Column(db.String(45), primary_key=True, default=str(uuid4()))

    这个就是对的,应该没有更好的办法。
    sugarkeek
        7
    sugarkeek  
    OP
       2019-11-15 11:02:15 +08:00
    @Latin #5 我试试
    @encro #6 好的好的,感谢
    ilittlesun
        8
    ilittlesun  
       2020-06-11 11:25:40 +08:00
    或者 id = db.Column(db.String(45), primary_key=True, autoincrement=True)
    sugarkeek
        9
    sugarkeek  
    OP
       2020-06-11 19:11:56 +08:00
    @ilittlesun 哈哈,很久之前的回答了。我后来查了 Flask Admin 的文档,他们目前只支持整数作为主键
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1084 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 18:39 · PVG 02:39 · LAX 11:39 · JFK 14:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.