1

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

我有 2 个实体,客户和客户列表,具有多对多关系。

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:

未定义全局名称“客户”

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

谢谢

4

3 回答 3

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
于 2010-05-11T12:18:21.587 回答
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))。(实际上有更多的魔法来确定你的意思是你有很多实体的属性,但它仍然使用简单的委托)

于 2010-05-11T16:02:56.483 回答
0

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

于 2010-05-11T12:20:40.090 回答