【问题标题】:Sqlalchemy+elixir: How query with a ManyToMany relationship?Sqlalchemy+elixir:如何查询多对多关系?
【发布时间】:2011-02-18 03:02:11
【问题描述】:

我将 sqlalchemy 与 Elixir 一起使用,但在尝试进行查询时遇到了一些麻烦..

我有 2 个实体,Customer 和 CustomerList,具有多对多关系。

customer_lists_customers_table = Table('customer_lists_customers', 
                      metadata,
                      Column('id', Integer, primary_key=True),
                      Column('customer_list_id', Integer, ForeignKey("customer_lists.id")),
                      Column('customer_id', Integer, ForeignKey("customers.id")))

class Customer(Entity):
  [...]
  customer_lists = ManyToMany('CustomerList', table=customer_lists_customers_table)

class CustomerList(Entity):
  [...]

  customers = ManyToMany('Customer', table=customer_lists_customers_table)

我正在尝试与一些客户一起查找 CustomerList:

customer = [...]
CustomerList.query.filter_by(customers.contains(customer)).all()

但我得到了错误: 名称错误:

未定义全局名称“客户”

客户似乎与实体字段无关,有一个特殊的查询表单可以处理关系(或多对多关系)?

谢谢

【问题讨论】:

    标签: python sqlalchemy python-elixir


    【解决方案1】:

    仔细阅读错误信息,它指出了问题的根源。你的意思是 CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all()?

    更新:使用声明式定义时,您可以在 class 范围内使用刚刚定义的关系,但这些属性在类外不可见:

    class MyClass(object):
        prop1 = 'somevalue'
        prop2 = prop1.upper() # prop1 is visible here
    
    val2 = MyClass.prop1 # This is OK    
    
    val1 = prop1.lower() # And this will raise NameError, since there is no 
                         # variable `prop1` is global scope
    

    【讨论】:

    • 是的,当然。我明白这一点,但为什么会发生呢?在所有其他情况下,我可以使用没有实体的字段。
    【解决方案2】:

    CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all() 应该可以正常工作。

    【讨论】:

      【解决方案3】:

      您可以使用常规过滤器:query.filter(CustomerList.customers.contains(customer))。有关更多示例,请参阅 SQLAlchemy 文档。实际上 filter_by 是一个特例。 query.filter_by(**kwargs) 简写只适用于简单的相等比较。在掩护下query.filter_by(foo="bar", baz=42) 被委派给query.filter(and_(MyClass.foo == "bar", MyClass.baz == 42)) 的等价物。 (实际上,要弄清楚您的意思是您有很多实体的哪个属性,实际上稍微有点神奇,但它仍然使用简单的委托)

      【讨论】:

        猜你喜欢
        • 2019-01-18
        • 2012-09-17
        • 2018-02-24
        • 2011-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多