2010-05-11 2 views
1

나는 Elixir에서 sqlalchemy를 사용하고 있으며 쿼리를 만들려고 몇 가지 어려움을 겪고 있습니다.Sqlalchemy + elixir : ManyToMany 관계로 쿼리하는 방법?

대다수의 관계가있는 Customer와 CustomerList라는 두 개의 엔터티가 있습니다.

global name 'customers' is not defined

고객이 엔티티 필드와 관련이없는 것 같다 :

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을 찾기 위해 tryng 해요 :

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

하지만 오류를 얻을 : 나가서 설명하자면 NameError를 , 관계 (또는 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

0

CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all() 잘 작동합니다.