r/FastAPI • u/Medium_Magazine_4994 • May 03 '23
Question I am a beginner who has recently started with fastapi, and I have some questions. Please let me know if you can help. Thank you.
I'm studying fastapi with ChatGPT. I am currently studying one-to-many foreign key relationships and would like some advice.
class Post:
...
comments = relationship("Comment", back_populates="post")
class Comment:
...
post_id = Column(ForeignKey("post.id"), nullable=False)
post = relationsihp("Post", back_populates="comments") When there are two existing classes like above
comment = Comment(content=content, post_id=post_id)
session.add(comment)
session.commit()
post = session.query(Post).filter_by(id=post_id).first()
post.comments.append(comment) do I need to use every time I register a comment?
ChatGPT says that if I don't do it that way, I won't be able to read
post = session.query(Post).filter_by(id=post_id).first()
post.comments However, even without using
post.comments.append(comment)I can still read it from the docs. So I'm wondering if ChatGPT is giving me the wrong information or if it's only visible in the docs
3
1
u/anseho May 03 '23
You have two ways of adding the comment:
Create an instance of the
Commentmodel with all the data needed, including the post ID. Add the new instance to the session and commit.Fetch the post record, create an instance of the
Commentmodel, and append it to post.comments. Add post to the session and commit. In this case, SQLAlchemy takes care of populating the value ofpost_idin the comment due to the relationship between the two.
When you use each approach? If you have an endpoint to add comments, something like POST /posts/{id}/comments, then you already have all the data you need to add the comment and can use the first approach. No need to fetch the post record.
The append method is more convenient when you're creating the two instances at the same time.
Bear in mind that relationship() is just a mechanism in SQLAlchemy that allows SQLAlchemy to infer the IDs of related objects, and takes care of pulling the related entities from the database without you having to query the comments separately.
Hope this helps!
-4
u/WafWoof May 03 '23
This doesn’t help with fastapi much, but I like the Requests library for outgoing http requests. Very simple and clean.
3
u/extreme4all May 03 '23 edited May 03 '23
you might want to read sqlalchemy documentation: https://docs.sqlalchemy.org/en/20/orm/queryguide/index.html
this parts get all the posts
session.query(Post)this part filters the posts by id
.filter_by(id=post_id)this part takes the first item from the results
.first()you don't need the filter but then you don't have much control over what post you want to return, as you'll just get all posts and take the first one this will create a comment
the cool thing about back_populate is that it will do the above for you if you have a post.