How to efficiently edding data with dependent Relationships in SQLAlchemy: Avoiding Overhead from Repeated Queries #11510
Unanswered
iancont
asked this question in
Usage Questions
Replies: 1 comment
-
I dont know that I'm following, there's a lot of terminology used here that I can't match up with what you're doing. Adding an Address - by "normalize", you mean match it to the correct user when you INSERT it? You do need to associate the object with the correct parent explicitly, SQLAlchemy would have no way of knowing that. I dont see what "query for each field" means, in your code I see one extra query for User which you could skip since you have that User already: def add_address_for_user(session, user, email):
# Create a new address for the user
new_address = Address(email=email, user=user)
session.add(new_address)
session.commit() # Commit to save the new address
# Adding the initial user
john_doe = User(name="John Doe")
session.add(john_doe)
session.commit()
# Now, add a new address for "John Doe"
add_address_for_user(session, john_doe, "john.new@example.com") im not sure what you mean otherwise |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi everyone,
I have a question about adding data to a normalized database using SQLAlchemy. Specifically, I'm wondering if I need to normalize the data first or if SQLAlchemy will handle the corresponding foreign keys automatically. How do I establish these add data relationships effectively?
This question applies when you want to add an instance of a class that depends on an attribute of another class, for which you may already have an existing instance.
Here's an example of what I'm working with:
I have been normalizing the data using Pydantic and performing a query for each field. However, this approach introduces significant overhead. Some instances of my models can take up to 5 seconds to create due to extensive querying of the database for distinct tables.
My main question is whether there is a simpler or more efficient way to handle this in SQLAlchemy. Do I need to create a custom method like
add_address_for_user
, or does SQLAlchemy provide a built-in or easier approach to managing these relationships and ensuring data normalization?Beta Was this translation helpful? Give feedback.
All reactions