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) &amp; \
           (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:  


In my comparator factory is_first method I can't get the actual instance, so I don't know which are the Model2s associated
In the same method I want to order my select against the weight attribute of Model2, and then take the first


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


Question: Centering on the decimal separator, figure font selection
Answer: 

\documentclass[12pt]{standalone}
\usepackage{dcolumn}  

\makeatletter  


\newcolumntype{O}[3]{&gt;{\everymath{\mathgroup\symletters}\DC@{#1}{#2}{#3}}c&lt;{\DC@end}}
\makeatother

\begin{document}


\begin{tabular}{cO..{-1}D..{-1}}
zzzz &amp; 1.1 &amp; 1.1\\
zzzz &amp; 1.12 &amp; 1.12\\
zzzz &amp; 2341.1 &amp; 2341.1\\
zzzz &amp; 1.1043 &amp; 1.1043
\end{tabular}
\end{document}