【问题标题】:SQLAlchemy get value from a table if not present in another one如果另一个表中不存在 SQLAlchemy,则从表中获取值
【发布时间】:2014-01-31 00:08:41
【问题描述】:

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

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

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

【问题讨论】:

    标签: python sqlalchemy pyramid


    【解决方案1】:

    在 SQL 中你可以左外连接表

    例如

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

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多