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

  • SEARCH
  • Home
  • 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 8829149
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T07:46:10+00:00 2026-06-14T07:46:10+00:00

Suppose I have a one-to-many relationship like this: class Book(Base): __tablename__ = books id

  • 0

Suppose I have a one-to-many relationship like this:

class Book(Base):
    __tablename__ = "books"
    id = Column(Integer)
    ...
    library_id = Column(Integer, ForeignKey("libraries.id"))

class Library(Base):
    __tablename__ = "books"
    id = Column(Integer)
    ...
    books = relationship(Book, backref="library")

Now, if I have an ID of a book, is there a way to retrieve it from the Library.books relationship, “get me a book with id=10 in this particular library”? Something like:

try:
    the_book = some_library.books.by_primary_key(10) 
except SomeException:
    print "The book with id 10 is not found in this particular library"

Workarounds I can think of (but which I’d rather avoid using):

book = session.query(Book).get(10)
if book and book.library_id != library_id:
    raise SomeException("The book with id 10 is not found in this particular library")

or

book = session.query(Book).filter(Book.id==10).filter(Book.library_id=library.id).one()

Reason: imagine there are several different relationships (scifi_books, books_on_loan etc.) which specify different primaryjoin conditions – manually querying would require writing individual queries for all of them, while SQLAlchemy already knows how to retrieve items for that relationship. Also, I’d prefer to load the books all at once (by accessing library.books) than issuing individual queries.

Another option, which works but is inefficient and inelegant is:

for b in library.books:
    if b.id == book_id:
        return b

What I’m currently using is:

library_books = {b.id:b for b in library.books}
for data in list_of_dicts_containing_book_id:
    if data['id'] in library_books:
        library_books[data['id']].do_something(data)
    else:
        print "Book %s is not in the library" % data['id']

I just hope there’s a nicer built-in way of quickly retrieving items from a relationship by their id

UPD: I’ve asked the question in the sqlalchemy mail list.

  • 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-06-14T07:46:11+00:00Added an answer on June 14, 2026 at 7:46 am

    SQLAlchemy’s query object has with_parent method which does exactly that:

    with_parent(instance, property=None)

    Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established relationship() configuration.

    so in my example the code would look like

    q = session.query(Book)
    q = q.with_parent(my_library, "scifi_books")
    q = q.filter(Book.id==10).one()
    

    This will issue a separate query though, even if the my_library.scifi_books relation is already loaded. There seems to be no "built-in" way to retrieve an item from an already-loaded relation by its PK, so the easiest is to just convert the relation to a dict and use that to look up items:

    book_lookup = {b.id: b for b in my_library.scifi_books}
    book = books_lookup[10]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have two models, Book and Page, such there is a one-to-many relationship
Suppose I have a string like this: one two three four five six seven
Suppose I have a dataframe like this one: df <- data.frame (id = c(a,
Suppose I have two entities: User and UserGroup . They have a one-to-many relationship
Suppose I have a model Person which has a one to many relationship with
I have two classes university and department, suppose there is one to many relationship
Suppose I have two tables in one to many relationship. And, I want to
Suppose i have a one to many relationship between two model entities Entity One
Suppose i have two tables with one to many relationship (association in EF 4.1)
I have 2 models, Users & Accounts. They are in one-to-many relationship, i.e. each

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.