2010-05-11 41 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()應該正常工作。