亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從sqlalchemy中的連接表中過濾?

如何從sqlalchemy中的連接表中過濾?

暮色呼如 2022-12-20 12:04:38
大家好,我是 sqlalchemy 的新手,我嘗試通過以下代碼從用戶輸入的任何字段中搜索模塊。    filters = []    if 'inputVendorName' in inputfield:        filters.append(Vendors.vendor_name.contains(inputfield['inputVendorName']))    if 'inputProductName' in inputfield:        filters.append(Product.product_name.contains(inputfield['inputProductName']))    if 'inputCustomerName' in inputfield:        filters.append(Customers.customer_name.contains(inputfield['inputCustomerName']))    if 'inputSalePrice' in inputfield:        filters.append(Sales.price.contains(inputfield['inputSalePrice']))    # jointable --> how to join table    results = jointable.query.filter(db.or_(*filters)).all()開頭fiters是一個列表,其中包含來自用戶的任何輸入值,我想在列表中使用這些值來從我的連接表中進行過濾。例如,用戶輸入了一些product_name,我想用它product_name來過濾并獲取Products表中匹配的任何記錄值,product_name并從與此“產品名稱”相關的另一個表(供應商、銷售、客戶)中獲取其他記錄。那我該怎么做呢?
查看完整描述

1 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

這是一段基于一組“動態”過濾器運行查詢的代碼。


filters = []


# this is an example: 

inputfield = {

    "inputVendorName": "J", 

    "inputProductName": "Pen", 

    "MinPrice": 10

}


if 'inputVendorName' in inputfield:

    filters.append(Vendor.vendor_name.contains(inputfield["inputVendorName"]))


if  'inputProductName' in inputfield:

    filters.append(Product.product_name.contains(inputfield["inputProductName"]))


if 'MinPrice' in inputfield:

    filters.append(Sale.price > inputfield["MinPrice"])


base_query = session.query(Customer, Product, Vendor, Sale).filter(

    Sale.customer_id == Customer.customer_id, Vendor.vendor_id == Product.vendor_id, Sale.product_id == Product.product_id)


for res in base_query.filter(*filters).all(): 

    print(res)


查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號