Michele Gargiulo
Michele Gargiulo

Reputation: 475

Flask-SQLAlchemy many-to-many ordered relationship in hybrid_property

I am trying to get the first object out of an ordered many-to-many relationship using Flask-SQLAlchemy.

I would like to accomplish this using hybrid properties, so I can reuse my code in a clean way.

Here is the code, with some comment:

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)

And the usage:

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

The problems are:

Something is not clear in my head, maybe there's a simpler solution?

Upvotes: 4

Views: 653

Answers (1)

jwogrady
jwogrady

Reputation: 1570

Perhaps looking at a working many-to-many example might help. Flask-Security is a great one.

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

Upvotes: 1

Related Questions