简体   繁体   English

如何从 sqlalchemy 中的连接表中过滤?

[英]How to filter from joined table in sqlalchemy?

在此处输入图像描述

Hello everyone, I'm very new with sqlalchemy and I try to do a searching module from any field that I input from the user by the below code.大家好,我是 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()

Begin with fiters is a list that contains any input value from the user, and I want to use these values in a list to filter from my join table.fiters的是一个列表,其中包含来自用户的任何输入值,我想在列表中使用这些值从我的连接表中过滤。

For example, the user has input some product_name and I want to use this product_name to filter and get any record value in Products table that matches to product_name and also gets the other record from another table (Vendors, Sales, Customers) that related to this 'product_name'.例如,用户输入了一些product_name ,我想使用这个product_name过滤并获取Products表中与product_name匹配的任何记录值,并从另一个表(供应商、销售、客户)中获取与此相关的其他记录'产品名称'。

So how can I do that?那么我该怎么做呢?

Here's a piece of code that runs a query, based on a set of 'dynamic' filters.这是一段基于一组“动态”过滤器运行查询的代码。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM