To insert or update related data in Flask/SQLAlchemy, you can follow these steps:
For example, consider a scenario where you have two tables - User and Address, with a one-to-many relationship (one user can have multiple addresses). Here are the steps to insert data into both tables:
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from app import db
class User(db.Model):
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
addresses = relationship("Address", back_populates="user")
class Address(db.Model):
id = Column(Integer, primary_key=True)
street = Column(String(50))
city = Column(String(50))
state = Column(String(2))
zip = Column(String(10))
user_id = Column(Integer, ForeignKey("user.id"))
user = relationship("User", back_populates="addresses")
user = User(name="John", age=30)
address1 = Address(street="123 Main St", city="Anytown", state="NY", zip="12345", user=user)
address2 = Address(street="456 Oak Ave", city="Anytown", state="NY", zip="12345", user=user)
db.session.add(user)
db.session.add(address1)
db.session.add(address2)
db.session.commit()
This will insert the new data into the database.
To update related data, you can modify the instances outside of the session and then use session.merge() to update the changes in the database:
# Retrieve the user instance from the database
user = db.session.query(User).filter_by(name="John").one()
# Update the name of the user
user.name = "Johnny"
# Update the zip code of the first address
user.addresses[0].zip = "54321"
# Merge the changes into the session and commit
db.session.merge(user)
db.session.commit()
This will update the related data in the database.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-04-24 11:00:00 +0000
Seen: 8 times
Last updated: Jan 29 '22
What is the method for programmatic access to a time series?
What is the procedure for using pg_restore on Windows with Docker?
Can SqlDependency be used in a programming language other than .NET, such as node js?
How can multiple queries be merged into a single stored procedure in MySQL?
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?