列表中列的 SQLAlchemy 多对一关系查询过滤器
SQLAlchemy Many-To-One relation query filter for column in list
我定义了以下模型:
class Attribute(Base):
__tablename__ = "attributes"
id = Column(BigInteger, primary_key=True, index=True)
data_id = Column(BigInteger, ForeignKey("data.art_no"))
name = Column(VARCHAR(500), index=True)
data = relationship("Data", back_populates="attributes_rel")
class Data(Base):
__tablename__ = "data"
art_no = Column(BigInteger, primary_key=True, index=True)
multiplier = Column(Float)
attributes_rel = relationship("Attribute", back_populates="data", cascade="all, delete, delete-orphan")
@property
def attributes(self):
return [attribute.name for attribute in self.attributes_rel]
如果我查询 Data
行,我会得到这些行(仅属性 属性:
#1 ['attributeX', 'attributeY']
#2 ['attributeZ']
#3 ['attributeX', 'attributeZ']
我现在想做以下事情:
我有这个列表 ['attributeX']
,我想查询我的数据并且只返回 Data
行,它具有 'attributeX'
属性。
如果我有这个列表 ['attributeX', 'attributeZ']
,我想查询我的数据并且只返回 Data
行,其中有 'attributeX'
AND 'attributeZ'
属性。
如何进行查询?
我试过 .filter(models.Data.attributes_rel.any(models.Attribute.name.in_(attributesList)))
其中 returns 所有行都具有 attributesList
中的任何属性....但我只想得到 models.Data
具有的行完全 列表中的属性(甚至其他属性,但至少是列表中的属性)
我的问题的光学样本:
这三个属性与 Data
行相关联。我已经设置了 attributeList=['Test2','Test3']
...但也返回了最后一行..因为它具有属性 Test3
但不应返回,因为它没有 Test2
...知道吗?
in_
基本上会做 any of the attributes is present
,而你想要的是 ALL attributes are present
.
为此,只需分别为每个属性名称添加过滤器:
q = session.query(Data)
for attr in attributesList:
q = q.filter(Data.attributes_rel.any(Attribute.name == attr))
我定义了以下模型:
class Attribute(Base):
__tablename__ = "attributes"
id = Column(BigInteger, primary_key=True, index=True)
data_id = Column(BigInteger, ForeignKey("data.art_no"))
name = Column(VARCHAR(500), index=True)
data = relationship("Data", back_populates="attributes_rel")
class Data(Base):
__tablename__ = "data"
art_no = Column(BigInteger, primary_key=True, index=True)
multiplier = Column(Float)
attributes_rel = relationship("Attribute", back_populates="data", cascade="all, delete, delete-orphan")
@property
def attributes(self):
return [attribute.name for attribute in self.attributes_rel]
如果我查询 Data
行,我会得到这些行(仅属性 属性:
#1 ['attributeX', 'attributeY']
#2 ['attributeZ']
#3 ['attributeX', 'attributeZ']
我现在想做以下事情:
我有这个列表 ['attributeX']
,我想查询我的数据并且只返回 Data
行,它具有 'attributeX'
属性。
如果我有这个列表 ['attributeX', 'attributeZ']
,我想查询我的数据并且只返回 Data
行,其中有 'attributeX'
AND 'attributeZ'
属性。
如何进行查询?
我试过 .filter(models.Data.attributes_rel.any(models.Attribute.name.in_(attributesList)))
其中 returns 所有行都具有 attributesList
中的任何属性....但我只想得到 models.Data
具有的行完全 列表中的属性(甚至其他属性,但至少是列表中的属性)
我的问题的光学样本:
这三个属性与 Data
行相关联。我已经设置了 attributeList=['Test2','Test3']
...但也返回了最后一行..因为它具有属性 Test3
但不应返回,因为它没有 Test2
...知道吗?
in_
基本上会做 any of the attributes is present
,而你想要的是 ALL attributes are present
.
为此,只需分别为每个属性名称添加过滤器:
q = session.query(Data)
for attr in attributesList:
q = q.filter(Data.attributes_rel.any(Attribute.name == attr))