Flask-SQLAlchemy在hybrid_property中有多对多的有序关系

时间:2014-06-10 17:28:48

标签: python flask sqlalchemy relationship flask-sqlalchemy

我正在尝试使用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.Integer, 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, primary_key=True, autoincrement=True)
  weight = db.Column(db.Integer, nullable=False, default=0)

用法:

Model1.query.filter(Model1.primary_model2 == Model2.query.get(1))

问题是:

  • 在我的比较器工厂中,is_first方法我无法获得实际的实例,所以我不知道哪个是Model2s关联的
  • 在同一方法中,我想根据Model2的权重属性对我的选择进行排序,然后采取第一个

我头脑中有些东西不清楚,也许有一个更简单的解决方案?

1 个答案:

答案 0 :(得分:1)

也许看一个工作多对多的例子可能有所帮助。 Flask-Security非常棒。

https://pythonhosted.org/Flask-Security/quickstart.html#sqlalchemy-application