python – 在hybrid_property中Flask-SQLAlchemy多对多有序关系
发布时间:2020-12-20 13:42:55 所属栏目:Python 来源:网络整理
导读:我正在尝试使用Flask-SQLAlchemy从有序的多对多关系中获取第一个对象. 我想使用混合属性来实现这一点,因此我可以以干净的方式重用我的代码. 这是代码,有一些评论: class PrimaryModel2Comparator(Comparator): def __eq__(self,other): return self.__claus
我正在尝试使用Flask-SQLAlchemy从有序的多对多关系中获取第一个对象.
我想使用混合属性来实现这一点,因此我可以以干净的方式重用我的代码. 这是代码,有一些评论: class PrimaryModel2Comparator(Comparator): def __eq__(self,other): return self.__clause_element__().model2s.is_first(other) class model2s_comparator_factory(RelationshipProperty.Comparator): def is_first(self,other,**kwargs): return isinstance(other,Model2) & (db.session.execute(select([self.prop.table])).first().id == other.id) model1_model2_association_table = db.Table('model1_model2_association',db.Column('model1_id',db.Integer,db.ForeignKey('model1s.id')),db.Column('model2_id',db.ForeignKey('model2s.id')),) class Model1(db.Model): __tablename__ = 'model1s' id = db.Column(db.Integer,primary_key=True,autoincrement=True) model2s = db.relationship('Model2',order_by=desc('Model2.weight'),comparator_factory=model2s_comparator_factory,secondary=model1_model2_association_table,backref=db.backref('model1s',lazy='dynamic'),lazy='dynamic' ) @hybrid_property def primary_model2(self): return self.model2s.order_by('weight desc').limit(1).one() @primary_model2.comparator def primary_model2(cls): return PrimaryModel2Comparator(cls) class Model2(db.Model): __tablename__ = 'model2s' id = db.Column(db.Integer,autoincrement=True) weight = db.Column(db.Integer,nullable=False,default=0) 用法: Model1.query.filter(Model1.primary_model2 == Model2.query.get(1)) 问题是: >在我的比较器工厂中is_first方法我无法得到实际的实例,所以我不知道哪个是Model2s关联的 我头脑中有些东西不清楚,也许有一个更简单的解决方案? 解决方法
也许看一个工作多对多的例子可能有所帮助. Flask-Security非常棒.
https://pythonhosted.org/Flask-Security/quickstart.html#sqlalchemy-application (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |