簡體   English   中英

Flask-SQLAlchemy如何在不運行查詢的情況下存儲查詢?

[英]Flask-SQLAlchemy how to store queries without running them?

所以我想出了這樣的東西:

def someFunction(carPool):
    dict = {
        'redcars': models.RedCar.query.all(),
        'bluecars': models.BlueCar.query.all(),
        'greencars': models.GreenCar.query.all()
    }
    cars = dict[carPool.lower()]

但是這里的問題是,每次調用此函數時,所有3個查詢都將運行,其結果將存儲在字典中。

因此,我想問是否有任何方法可以執行類似的操作,但又不運行所有查詢或不編寫大量if-elses?

在研究方法重現switch語句的Stack Overflow時,我遇到了一個解決方案,該解決方案的字典使用lambda函數作為值,因此我想到了:

def someFunction(carPool):
    dict = {
        'redcars': lambda _: models.RedCar.query.all(),
        'bluecars': lambda _: models.BlueCar.query.all(),
        'greencars': lambda _: models.GreenCar.query.all()
    }
    cars = dict[carPool.lower()]('random var')

也許這不是最好的解決方案,但是它可以完成工作,所以我將其留在這里,也許其他人會發現它很有用,並節省了一些代碼行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM