【问题标题】:Flask-SQLAlchemy many-to-many ordered relationship in hybrid_propertyhybrid_property 中的 Flask-SQLAlchemy 多对多有序关系
【发布时间】:2014-07-31 14:11:48
【问题描述】:

我正在尝试使用 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 方法中,我无法获取实际实例,所以我不知道关联的 Model2 是哪些
  • 以同样的方法,我想根据 Model2 的权重属性排序我的选择,然后取第一个

我脑子里有些不清楚,也许有更简单的解决方案?

【问题讨论】:

    标签: python flask sqlalchemy relationship flask-sqlalchemy


    【解决方案1】:

    也许查看一个有效的多对多示例可能会有所帮助。 Flask-Security 非常棒。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-15
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2019-01-12
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多