我正在使用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()
但我收到错误: NameError:
全局名称'customers'未定义
客户似乎与实体字段无关,有一种特殊的查询形式可以处理关系(或ManyToMany关系)?
由于
答案 0 :(得分: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
答案 1 :(得分: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))
。 (实际上有更多的魔法来确定你认为你有多个实体的属性,但它仍然使用简单的委托)
答案 2 :(得分:0)
CustomerList.query.filter_by(CustomerList.customers.contains(customer)).all()
应该可以正常使用。