推荐学习书目
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
hastelloy
V2EX  ›  Python

Flask Achemy 的 Model 怎么优雅的做简单查询和计算

  •  
  •   hastelloy · Apr 28, 2018 · 2556 views
    This topic created in 2953 days ago, the information mentioned may be changed or developed.

    通过关系查找 ForeignKey 的字段值,简单计算本身的字段值,比如下面的查找到 Part 的重量,根据单位价格计算总价,把这个写在 Model 中合适吗?看文档中好像没有相关的例子,这种情况应该很常见吧

        class Part(db.Model):
            ...
            id = db.Column(db.Integer, primary_key=True)
            weight = db.Column(db.Float, nullable=False)
            ...
    
        class Quote(db.Model):
            ...
            unit_price = db.Column(db.Float, nullable=False)
            part_id = db.Column(db.Integer, db.ForeignKey("part.id"))
            part = db.relationship("Part", backref=db.backref('quotes', lazy=False))
            price = db.Colum(db.Float)
            ...
    
            def cal_price(self):
                p = Part.query.filter_by(Part.id=self.part_id).first()
                self.price = p.weight*self.unit_price
    
    1 replies    2018-05-02 11:08:39 +08:00
    vipppppp
        1
    vipppppp  
       May 2, 2018
    好像没什么毛病
    不过建了外键了,为啥不直接 p = self.part
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   934 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 19:17 · PVG 03:17 · LAX 12:17 · JFK 15:17
    ♥ Do have faith in what you're doing.