繁体   English   中英

sqlalchemy 关系的过滤子

[英]Filter child of sqlalchemy relationship

我正在构建一个显示不同植物物种数据库的应用程序。 除了“注释”列,每个用户都可以看到相同的植物物种表,每个用户都可以根据自己的喜好对其进行编辑。 这是我创建的数据库结构:

from datetime import datetime
import sqlalchemy as sa 
from sqlalchemy import create_engine 
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("sqlite:///:memory:", echo=False)
Session = sessionmaker(bind=engine) 
session = Session() 
Base = declarative_base()

class Note(Base): 
    __tablename__ = "note"
    id = sa.Column(sa.Integer, primary_key=True) 
    content = sa.Column(sa.Text(), nullable=False) 
    plant_id = sa.Column(sa.Integer, sa.ForeignKey("plant.id")) 
    user_id = sa.Column(sa.Integer, sa.ForeignKey("profile.id"))

    def __repr__(self):
        return f"<{self.id} -> {self.content}, user: {self.user_id}>"

class Plant(Base): 
    __tablename__ = "plant" 
    id = sa.Column(sa.Integer, primary_key=True) 
    common_name = sa.Column(sa.String(200), nullable=False) 
    date_created = sa.Column(sa.DateTime, default=datetime.utcnow) 
    notes = relationship("Note", backref="user_notes")

    def __repr__(self):
        return f"<{self.common_name}; n: {self.notes}>"

class Profile(Base): 
    __tablename__ = "profile" 
    id = sa.Column(sa.Integer, primary_key=True) 
    username = sa.Column(sa.String(200), unique=True, nullable=False)

Base.metadata.create_all(engine)

profile1 = Profile(username="profile1") 
profile2 = Profile(username="profile2") 
session.add(profile1) 
session.add(profile2) 
session.commit()

plant1 = Plant( common_name="plant1", notes=[ Note( content="plant1 note1", user_id=profile1.id ),  Note( content="plant1 note2", user_id=profile2.id )  ] ) 
plant2 = Plant( common_name="plant2", notes=[ Note( content="plant2 note2", user_id=profile2.id ) ] ) 
session.add(plant1) 
session.add(plant2) 
session.commit()

我试图为用户 2 获取所有植物,这意味着编写一个查询来过滤掉其他用户的所有笔记(在示例用户 1 中)。

我努力了:

session.query(Plant).filter(Plant.notes.any(user_id=profile2.id)).all()

不幸的是,这也给了我用户 1 的注释,我该如何为此编写正确的查询?

我解决了它:

    plants = Plant.query.order_by(Plant.date_created).all()
    for i , plant in enumerate(plants):
        user_notes = [n for n in plant.notes if n.user_id == USER_ID]
        plants[i].notes = user_notes

还有一种 sql 方法来过滤这个吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM