Is it possible to add to a SQLAlchemy relationship using ids rather than objects?
For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:
class Review(Base):
artist_id = Column(Integer, ForeignKey('artist.id'))
artist = relationship(Artist, backref=backref('reviews', order_by=id))
# etc.
class Artist(Base):
# etc.
With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:
for review_id in review_ids:
review = session.query(Review).filter(Review.id==review_id).first()
artist.reviews.append(review)
I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?
The sqlalchemy backref is one of the type keywords and it passed as the separate argument parameters which has to be used in the ORM mapping objects. It mainly includes the event listener on the configuration attributes with both directions of the user datas through explicitly handling the database relationships.
A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.
Python Flask and SQLAlchemy ORM Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.
Your best bet is probably to compose an update
expression against the backing tables. Otherwise, you can't really modify a Review
without actually querying for it (and that's what your doing; you aren't actually modifying the Artist
at all).
Assuming Review.id
is the primary key, That would roughly be:
conn = session.connection()
conn.execute(Review.__table__
.update()
.values(artist_id=artist_id)
.where(Review.id.in_(review_ids))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With