Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 526523
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T08:47:09+00:00 2026-05-13T08:47:09+00:00

I have a SQLAlchemy model with a one-to-many relationship between table x and table

  • 0

I have a SQLAlchemy model with a one-to-many relationship between table x and table y. The record (if any) with the greatest id in table y where y.x_id = x.id is special. Class X and class Y map tables x and y.

I know how to define X.all_y (ORDER BY y.id). How do I define X.latest_y equivalent to X.all_y[-1]?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T08:47:10+00:00Added an answer on May 13, 2026 at 8:47 am

    the purely relational way to do it requires using a subquery to get the “latest” or “max” value, correlated to the parent, then equating that with the members of the collection. It means you’ll get best results if you put an index on the column that determines “the latest”:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    
    engine = create_engine('sqlite:///:memory:', echo='debug')
    
    m = MetaData()
    
    parent = Table('parent', m, 
                    Column('id', Integer, primary_key=True)
    )
    
    child = Table('child', m, 
                    Column('id', Integer, primary_key=True),
                    Column('parent_id', Integer, ForeignKey('parent.id')),
                    Column('sortkey', Integer)
                    )
    
    m.create_all(engine)
    
    class Parent(object):
        def __init__(self, children):
            self.all_c = children
    
    class Child(object):
        def __init__(self, sortkey):
            self.sortkey = sortkey
    
    latest_c = select([func.max(child.c.sortkey)]).\
                    where(child.c.parent_id==parent.c.id).\
                    correlate(parent).\
                    as_scalar()
    
    mapper(Parent, parent, properties={
        'all_c':relation(Child),
        'latest_c':relation(Child, 
                                primaryjoin=and_(
                                    child.c.sortkey==latest_c, 
                                    child.c.parent_id==parent.c.id
                                ),
                                uselist=False
        )
    })
    
    mapper(Child, child)
    
    session = sessionmaker(engine)()
    
    p1, p2, p3 = Parent([Child('a'), Child('b'), Child('c')]), \
                    Parent([Child('b'), Child('c')]),\
                    Parent([Child('f'), Child('g'), Child('c')])
    
    session.add_all([p1, p2, p3])
    session.commit()
    
    assert p1.latest_c.sortkey == 'c'
    assert p2.latest_c.sortkey == 'c'
    assert p3.latest_c.sortkey == 'g'
    

    Alternatively, you can on some platforms use LIMIT, which can produce faster results since you avoid the aggregation and can join the collection item on its primary key:

    latest_c = select([child.c.id]).\
                    where(child.c.parent_id==parent.c.id).\
                    order_by(child.c.sortkey.desc()).\
                    limit(1).\
                    correlate(parent).\
                    as_scalar()
    
    mapper(Parent, parent, properties={
        'all_c':relation(Child),
        'latest_c':relation(Child, 
                                primaryjoin=and_(
                                    child.c.id==latest_c, 
                                    child.c.parent_id==parent.c.id
                                ),
                                uselist=False
        )
    })
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 454k
  • Answers 454k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer _parameters is a NSDictionary that seems to be defined previously… May 15, 2026 at 9:57 pm
  • Editorial Team
    Editorial Team added an answer Why not just create a set of UIButton objects stacked… May 15, 2026 at 9:57 pm
  • Editorial Team
    Editorial Team added an answer programs written in assembler on windows are not binary compatible… May 15, 2026 at 9:57 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.