r/FastAPI • • May 16 '22

Question please help me aout fastapi/sqlqlachemy question

https://stackoverflow.com/questions/72258451/how-to-query-a-one-to-many-relationship-in-sqlalchemy-without-duplicates
2 Upvotes

4 comments sorted by

1

u/Ordinary_Bee_1547 May 16 '22

Hi,

Could you perhaps share a bit more of your codebase, e.g. link to Github so it could be cloned and checked more easily?

I only assumed this is the structure for your User class, but I do think you need to add relationship to both Post and Comment class which reference eachother.

class User(Base):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True, nullable=False)
    username = Column(String, nullable=False)
    created_at = Column(TIMESTAMP(timezone=True), nullable=False, default=text("NOW()"))
    email = Column(String, nullable=False)
    is_super_user = Column(Boolean, nullable=False)
    password = Column(String, nullable=False)
    is_admin = Column(Boolean, nullable=False)


class Post(Base):
    __tablename__ = "posts"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, default=False)
    created_at = Column(TIMESTAMP(timezone=True), nullable=False, default=text("NOW()"))
    owner_id = Column(Integer, ForeignKey(User.id, ondelete="CASCADE"), nullable=False)
    comments = relationship("Comment", backref="post_details")


class Comment(Base):
    __tablename__ = "comments"

    id = Column(Integer, primary_key=True, nullable=False)
    email = Column(String, nullable=True)
    name = Column(String, nullable=True)
    content = Column(String, nullable=False)
    commented_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text("NOW()"))
    post_id = Column(Integer, ForeignKey(Post.id, ondelete="CASCADE"), nullable=False)
    post_details = relationship("Post", backref="comments")

1

u/Potential_League_178 May 17 '22

I'll try that but I'm not sure it's gonna give me what I want and I'm gonna put it on GitHub and share the link

1

u/Ordinary_Bee_1547 May 17 '22

I am curious how your schemas look like also. Often the issue lies there. Waiting to see the rest of the code.

1

u/_ragequilt_ May 19 '22

My understanding based on your question is that you want to query a list of posts which includes the information about the User and the Comments associated with the post.

If that is the case then instead of loading all three entities you could choose to create a relationship between the Post and User (referenced by the owner_id)

Since you're question does not offer details about whether a Post can exist without a User you can use the following query to fetch posts associated to a user.

from sqlalchemy.orm import joinedload, contains_eager

posts: Post = (
    db.query(Post)      
      .join(Post.user, User.id == Post.owner_id)
      .options(contains_eager(Post.user))
      .options(joinedload(Post.comments))
      .order_by(Post.id.desc())
      .all()
    )

If an association is created between Post and User then User.id == Post.owner_id becomes redundant and can be skipped.

The comments are simply eager loaded based on the relationship. The join is only needed if there is no explicit relationships defined.

Both contains_eager and joinedload can be a bit tricky if you're new to sqlalchemy.

The TLDR version is that you'd use contains_eager where you've already instructed SqlAlchemy to load data with a join. In our case that would be the join(Post.user, User.id == Post.owner_id) while joinedload simply uses the defined relationships to eager load the association.

  1. contains_eager

  2. joinedload