代码之家  ›  专栏  ›  技术社区  ›  Cyril N.

SQLAlchemy-作为子查询结果的列

  •  0
  • Cyril N.  · 技术社区  · 4 年前

    我有两个由SQLAlchemy管理的表,如下所示:

    class Contact(db.Model):
        __tablename__      = 'contacts'
    
        id                  = db.Column(db.Integer, primary_key=True, autoincrement=True)
    
        name                = db.Column(db.String(250), nullable=True, default=None)
        email               = db.Column(db.String(250), nullable=False)
    
        last_posted_message = db.SubQuery('SELECT created FROM messages WHERE contact_id = {current_alias}.id ORDER BY created DESC LIMIT 1')
    
    
    class Message(db.Model):
        __tablename__      = 'messages'
    
        id                  = db.Column(db.Integer, primary_key=True, autoincrement=True)
    
        message             = db.Column(db.String(250), nullable=False)
        created             = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)
    
        contact_id          = db.Column(db.Integer, db.ForeignKey('contacts.id'))
    

    last_posted_message ,要求SQLAlchemy为该特定列执行子查询。这在SQL查询中很容易实现,如下所示:

    'SELECT c.id, c.name, c.email, (SELECT created FROM messages WHERE contact_id = c.id ORDER BY created DESC LIMIT 1) AS last_posted_message FROM contacts c'
    

    所以我希望它可以通过SQLAlchemy实现,不会有很多麻烦。

    我试着在网上搜索,但没有成功。

    0 回复  |  直到 4 年前