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

Flask-sqlalchemy 自身引用的写法?

  •  
  •   bbhj3434 · 2014-03-22 16:18:56 +08:00 · 3883 次点击
    这是一个创建于 3681 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近在学 flask 和 sqlalchemy,死咬英文文档好累……
    这个问题找了比较久了,不知道有没有人清楚的。

    一个表的自身引用,字段:
    id name toplevel onlevel_id
    (主键) (名称) (大分类,bool) (上级分类)

    目前想实现的是:

    添加记录:

    toplevel 为 True ,onlevel_id 为 0

    toplevel 为 False ,onlevel_id 为某一个 toplevel 为 True 的 id

    查询记录:

    查询 toplevel 为 True 的记录 select.sub_category 为其下级分类列表

    我的水平还是太低了。。
    4 条回复    1970-01-01 08:00:00 +08:00
    ryanhust
        2
    ryanhust  
       2014-03-22 17:18:58 +08:00
    1L正解
    bbhj3434
        3
    bbhj3434  
    OP
       2014-03-22 21:15:29 +08:00
    @yinian1992 >_< 感谢你的帮助呢~还有一个问题,ForeignKey 有 类似 required 这个必定要输入值的参数吗?找一下没有说到这个,只有 nullable
    bbhj3434
        4
    bbhj3434  
    OP
       2014-03-22 21:27:59 +08:00
    @bbhj3434 打错字,应该是检查外键成立

    class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False, unique=True)
    top = db.Column(db.Boolean, nullable=False)
    on_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    top_category = db.relationship('Category', backref='sub_category', remote_side=[id])

    我现在的表如上,可是有个问题:on_id 这个字段随意一个不存在的id或空值都可以写入。。。
    ForeignKey 这个有 required 这种参数吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1011 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:51 · PVG 02:51 · LAX 11:51 · JFK 14:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.