gpt4 book ai didi

python - 如果另一个表中不存在,则 SQLAlchemy 从表中获取值

转载 作者:行者123 更新时间:2023-11-28 19:22:45 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:

class Property(Base):
name = Column(String(50))
default_value = Column(String(50))

class AssociatedProperty(Base):
property_id = Column(Integer, ForeignKey('properties.id'), primary_key=True)
collector_id = Column(Integer, ForeignKey('collectors.id'), primary_key=True)
property = relationship("Property", backref="ass_prop")
value = Column(String(50))

class Collector(Base):
properties = relationship("AssociatedProperty",
cascade="all, delete, delete-orphan",
lazy="dynamic",
backref="owner")

def get_properties(self, list_of_names):
"""
When called from a CollectorA instance i need to get all CollectorA name/value pairs.
When called from a CollectorB instance i need to get all CollectorB name/Value pairs and when a property name is not present i search in collectorA properties.
If not present in CollectorA's properties i return the property's default value.
"""

class CollectorA(Collector):
collectors_b = relationship("CollectorB", backref='owner', foreign_keys="[CollectorB.collector_a_id]")


class CollectorB(Collector):
collector_a_id = Column(Integer, ForeignKey('collectors_a.id'))
pass

我正在尝试使用最少数量的查询来实现此行为,但我不确定如何以优雅的方式执行此操作。感谢您的帮助。

最佳答案

在 SQL 中,您可以对表进行左外连接

例如

select tableA.value 
from tableA
left join tableB on tableA.value = tableB.value
where tableB.value is null

关于python - 如果另一个表中不存在,则 SQLAlchemy 从表中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21071081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com