2010-05-11 43 views
1

我正在使用sqlalchemy与药剂,并有一些麻烦试图作出查询..Sqlalchemy + elixir:如何使用ManyToMany关系进行查询?

我有2个实体,客户和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) 

我tryng找到CustomerList一些客户:

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

但我得到的错误: NameError:

global name 'customers' is not defined

客户似乎是无关的实体领域,有一个特殊的查询表单可以处理关系(或ManyToMany关系)?

感谢

回答

1

您可以使用常规过滤器: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))。 (实际上有更多的魔法来确定哪个属性意味着你有很多实体,但它仍然使用简单的授权)

1

阅读与关注的错误信息,它指向的问题根源。你的意思是 CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all()

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

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 
+0

是的,当然。我明白,但为什么会发生?在所有其他情况下,我可以使用不带实体的 字段。 – Hugo 2010-05-11 12:22:14

0

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