簡體   English   中英

如何將帶有 WHERE 子句的 SQL 作為子查詢轉換為 SQLAlchemy

[英]How to convert SQL with WHERE clause as subquery to SQLAlchemy

class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(50))
    
    posts_to_tags = relationship(
        "PostsToTags", back_populates="post", cascade="all,delete")
class Tag(Base):
    __tablename__ = "tags"
    id = Column(Integer, primary_key=True, index=True)
    tag = Column((String(50)), index=True)

    posts_to_tags = relationship(
        "PostsToTags", back_populates="tag", cascade="all,delete")
class PostsToTags(Base):

    __tablename__ = "posts_to_tags"

    id = Column(Integer, primary_key=True, index=True)
    post_id = Column(Integer, ForeignKey(
        "posts.id", ondelete="CASCADE"), index=True)
    post = relationship("Post", back_populates="posts_to_tags")

    tag_id = Column(Integer, ForeignKey(
        "tags.id", ondelete="CASCADE"), index=True)
    tag = relationship("Tag", back_populates="posts_to_tags")

我的嘗試:

        q = session.query(Post)
        if tags:
            tag_id_list = []
            for tag in tags:
                tag = session.query(Tag).filter(Tag.tag == tag).first()
                tag_id_list.append(tag.id)

            q = q.join(PostsToTags, Post.id == PostsToTags.post_id)

            q = q.filter(PostsToTags.tag_id.in_(tag_id_list))

我需要在 python 中創建一個空數組來存儲tag_id_list 我知道這不是最好的,因為在 MYSQL 中。非常清楚:

SELECT DISTINCT p.id, p.title, p.body, p.created_at
FROM posts p INNER JOIN posts_to_tags ptt ON p.id = ptt.post_id
WHERE 
    (
    SELECT t.tag
    FROM tags t
    WHERE t.id = ptt.tag_id
    )
IN ("animal", "people")

我無法理解 SQL 查詢。 有一些帖子有兩個標簽:(“動物”,“人”)

但是在我的代碼中。 沒有重復::

例如:

  • 約翰-#people
  • 彼得-#people
  • 狗-#animal
  • 貓-#animal
  • 約翰老虎 - #people #animal

然后使用我在 Python 中的代碼:

tags = ["people", "animal"] ->result: John, Peter, Dog, Cat, John Tiger

並使用 SQL 查詢:

tags = ["people", "animal"] ->result: John, Peter, Dog, Cat, John Tiger, John Tiger

所以“John Tiger”的復制品。

所以我的問題:

  • 不同結果的原因是什么
  • 編寫 SQLAlchemy 的最佳方法不必創建空數組。 我嘗試了子查詢之類的東西,但是由於理解錯誤,我無法編寫出沒有錯誤的好代碼。

您已經完成了設置 ORM 的艱苦工作,好好利用它吧。

像這樣的東西應該能讓你得到正確的帖子:

tags = ["people", "animal"]
q = (
    session.query(Post)
    .where(
        Post.posts_to_tags.any(
            PostToTags.tag.has(
                Tag.tag.in_(tags)
            )
        )
    )
)

還要查找關聯表 您的PostToTags表可以不可見,這樣您就可以直接訪問Post.tags作為關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM