title: Using Declarative syntax, how do I define a relationship representing the latest object in a many-to-one collection?
body: <p>I'm using SQLAlchemy's declarative syntax and I'd like to specify a relationship that provides the latest (max primary id) element in a collection. I've found this post: <a href="https://stackoverflow.com/questions/1930864/how-do-i-define-a-sqlalchemy-relation-representing-the-latest-object-in-a-collect">How do I define a SQLAlchemy relation representing the latest object in a collection?</a> but I'm having a tough time using this pattern, creating a subquery using Declarative only. Any pointers or help would be greatly appreciated!</p>
  
  <p>General Idea:</p>
  
  <pre><code>from sqlalchemy.ext.declarative import declarative_base
  Base = declarative_base(bind=engine, metadata=metadata)
  
  from sqlalchemy import *
  from sqlalchemy.orm import *
  
  class NewsPaper(Base):
      __tablename__ = "newspapers"
      id = Column(Integer, nullable=False, primary_key=True)
      name = Column(String(255))
      latest_article = relationship("Article",
                                  primaryjoin="(Article.newspaper_id==NewsPaper.id) &amp;"
                                                 "(Article.id==SUBQUERY_FOR_LATEST_ID)")
      def __repr__(self):
          return '''&lt;name={0}&gt;'''.format(self.name)
  
  
  class Article(Base):
      __tablename__ = "articles"
      id = Column(Integer, nullable=False, primary_key=True)
      title = Column(String(255))
      newspaper_id =  Column(Integer, ForeignKey('newspapers.id'))
      newspaper = relationship("NewsPaper", backref=backref('articles') )
  
      def __repr__(self):
          return '''&lt;title={0}&gt;'''.format(self.title)
  </code></pre>