好吧,我经历了一下,尝试在Northwind数据库上尝试,它看起来很有希望。虽然,我必须添加关系字段才能跟踪数据库关系。
让我们考虑一下,在启动应用程序时我不知道表之间的关系,因此我需要一种自动生成的方法。
import unittestfrom sqlalchemy import *from sqlalchemy.orm import create_sessionfrom sqlalchemy.ext.declarative import declarative_basefrom datetime import datetimefrom sqlalchemy.orm import contains_eager, joinedloadfrom sqlalchemy.orm import relationship#Create and engine and get the metadatabase = declarative_base()engine = create_engine('mssql://user:pass@Northwind', echo=True)metadata = metaData(bind=engine)#Reflect each database table we need to use, using metadataclass Customer(base): __table__ = Table('Customers', metadata, autoload=True) orders = relationship("Order", backref="customer")class Shipper(base): __table__ = Table('Shippers', metadata, autoload=True) orders = relationship("Order", backref="shipper")class Employee(base): __table__ = Table('Employees', metadata, autoload=True)# orders = relationship("Order", backref="employee") territories = relationship('Territory', secondary=Table('Employeeterritories', metadata, autoload=True))class Territory(base): __table__ = Table('Territories', metadata, autoload=True) region = relationship('Region', backref='territories')class Region(base): __table__ = Table('Region', metadata, autoload=True)class Order(base): __table__ = Table('Orders', metadata, autoload=True) products = relationship('Product', secondary=Table('Order Details', metadata, autoload=True)) employee = relationship('Employee', backref='orders')class Product(base): __table__ = Table('Products', metadata, autoload=True) supplier = relationship('Supplier', backref='products') category = relationship('Category', backref='products')class Supplier(base): __table__ = Table('Suppliers', metadata, autoload=True)class Category(base): __table__ = Table('Categories', metadata, autoload=True)class Test(unittest.TestCase): def setUp(self): #Create a session to use the tables self.session = create_session(bind=engine) def tearDown(self): self.session.close() def test_withJoins(self): q = self.session.query(Customer) q = q.join(Order) q = q.join(Shipper) q = q.filter(Customer.CustomerID =='ALFKI') q = q.filter(Order.OrderID=='10643') q = q.filter(Shipper.ShipperID=='1') q = q.options(contains_eager(Customer.orders, Order.shipper)) res = q.all() cus = res[0] ord = cus.orders[0] shi = ord.shipper self.assertEqual(shi.Phone, '(503) 555-9831')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)