我有一个多对一的关系数据库。在我的声明系统中,我打电话给relationship(),如下例所示。出于某种原因,我想保留所有Features
排序。不幸的是,排序逻辑非常复杂,并且使用多个属性来完成。如何在SQLAlchemy关系()中使用sortedcontainers.SortedList?
from sortedcontainers import SortedList
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Text
from sqlalchemy import ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(Text)
class Feature(Base):
__tablename__ = 'features'
id = Column(Integer, primary_key=True, autoincrement=True)
productid = Column(Integer, ForeignKey('products.id'))
attr = Column(Integer)
product = relationship('Product', back_populates='features')
Product.features=relationship('Feature', collection_class=SortedList, back_populates='product')
def __eq__(self, other):
# some magic here, simplified...
return self.attr == other.attr
def __lt__(self, other):
# some magic here, simplified...
return self.attr < other.attr
def __le__(self, other):
# some magic here, simplified...
return self.attr <= other.attr
engine = create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
Base.metadata.create_all(engine)
我已经充满了下列值的数据库:
sqlite> select * from products;
id name
---------- ----------
1 Product1
sqlite> select * from features;
id productid attr
---------- ---------- ----------
1 1 42
2 1 1
当我尝试加载(通过访问)的值,sortedcontainers.SortedList引发一个ValueError异常,大概是因为它正在尝试加载无序结果。当功能按顺序存储时,没有问题。
In [1]: from test import *
In [2]: session = Session()
In [3]: p = session.query(Product).first()
In [4]: for f in p.features:
print("id: %d\tattr: %d" % (f.id, f.attr))
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
# traceback
ValueError: <test.Feature object at 0x7f68da5d2208> not in sort order at index 1
我知道在这个特殊的情况下,解决方案是使用relationship
()的说法order_by
但我的使用情况是更复杂,因为排序使用几个列的值。
那么,有没有我错过了使用SQLAlchemy或我应该尝试找到一种解决方法?