基于记录数据的SqlAlchemy模型关联

发布于 2025-01-01 22:33:48 字数 491 浏览 2 评论 0原文

有一个 info 表,它与 car 表或 suv 表有关系。

它在 info.type 字段中指定。

那么如何根据记录的类型数据动态创建关联呢?

class Info(Base):
    item_id = Column(ForeignKey('cars-or-suvs-table.id'))
    type = Column(String())

class Car(Base):
    - data - 

    info = relationship('Info', backref="car")

class Suv(Base):
    - data - 

    info = relationship('Info', backref="suv")

编辑:我的表已经填充了数据,所以我无法更改数据库架构。

There is an info table and it has relationship to car table or suvtable.

Itis specified in info.type field.

So how can I create association on fly based on the type data of the record?

class Info(Base):
    item_id = Column(ForeignKey('cars-or-suvs-table.id'))
    type = Column(String())

class Car(Base):
    - data - 

    info = relationship('Info', backref="car")

class Suv(Base):
    - data - 

    info = relationship('Info', backref="suv")

Edit: I already have the tables filled with data, so I can not change db schema.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉梦枕江山 2025-01-08 22:33:48

由于您正在寻找不需要将外键移动到不同表的解决方案,因此您可以尝试以下方法:

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import sql
Base = declarative_base()
engine = sqlalchemy.create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()

class Info(Base):
    __tablename__ = 'info'
    id = Column(Integer(), primary_key=True)
    type = Column(String())
    item_id = Column(Integer())

    @property
    def item(self):
        if self.type == 'car':
            return self._car
        elif self.type == 'suv':
            return self._suv
        return None

    @item.setter
    def item(self, value):
        if value is not None:
            self.item_id = value.id
            self.type = value.__tablename__
        else:
            self.item_id = None

class Car(Base):
    __tablename__ = 'car'
    id = Column(Integer(), primary_key=True)
    info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'car'), foreign_keys=Info.item_id, uselist=False, backref='_car')

class Suv(Base):
    __tablename__ = 'suv'
    id = Column(Integer(), primary_key=True)
    info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'suv'), foreign_keys=Info.item_id, uselist=False, backref='_suv')

我将 Info.car 重命名为 Info._car,因为 ._car 将不可避免地成为伪造的汽车对象,即使 .类型是“suv”。

为了保持简单,我保留了事件侦听器的内容,但是您绝对可以从我的其他答案中调整您需要的部分,以避免事情陷入不一致的状态。

Since you're looking for a solution that doesn't require moving the foreign key to a different table, you can try this approach:

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import sql
Base = declarative_base()
engine = sqlalchemy.create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()

class Info(Base):
    __tablename__ = 'info'
    id = Column(Integer(), primary_key=True)
    type = Column(String())
    item_id = Column(Integer())

    @property
    def item(self):
        if self.type == 'car':
            return self._car
        elif self.type == 'suv':
            return self._suv
        return None

    @item.setter
    def item(self, value):
        if value is not None:
            self.item_id = value.id
            self.type = value.__tablename__
        else:
            self.item_id = None

class Car(Base):
    __tablename__ = 'car'
    id = Column(Integer(), primary_key=True)
    info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'car'), foreign_keys=Info.item_id, uselist=False, backref='_car')

class Suv(Base):
    __tablename__ = 'suv'
    id = Column(Integer(), primary_key=True)
    info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'suv'), foreign_keys=Info.item_id, uselist=False, backref='_suv')

I renamed Info.car to Info._car since ._car will unavoidably be a bogus car object even if .type is 'suv'.

I've left the event listener stuff out to keep it simple, but you can definitely adapt what pieces you need from my other answer to avoid things getting into an inconsistent state.

别把无礼当个性 2025-01-08 22:33:48

在 SQL 中,外键必须映射到一个特定的表,因此您需要将外键放在指向“info.id”的“car”或“suv”表中。

对于您所需要的来说,这可能有点过分了,但这里有一种解决方法(假设您实际上希望每辆车只有一个信息):

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import event
Base = declarative_base()

class Info(Base):
    __tablename__ = 'info'
    id = Column(Integer(), primary_key=True)
    type = Column(String())
    # NOTE: can't use backref='info' because we need the attributes defined
    #   directly on both classes so we can attach event listeners
    car = relationship('Car', back_populates='info', uselist=False)
    suv = relationship('Suv', back_populates='info', uselist=False)

    @property
    def item(self):
        # could check self.type here if you wanted
        return self.car or self.suv

    @item.setter
    def item(self, value):
        if isinstance(value, Car):
            self.car = value
        elif isinstance(value, Suv):
            self.suv = value
        elif value is None:
            self.car = None
            self.suv = None
        else:
            raise ValueError("item must be Car or Suv")

@event.listens_for(Info.car, 'set')
def _car_set_event(target, value, oldvalue, initiator):
    if value is not None:
        target.type = 'car'
        if target.suv:
            target.suv = None
    elif target.type == 'car':
        target.type = None

@event.listens_for(Info.suv, 'set')
def _suv_set_event(target, value, oldvalue, initiator):
    if value is not None:
        target.type = 'suv'
        if target.car:
            target.car = None
    elif target.type == 'suv':
        target.type = None

class Car(Base):
    __tablename__ = 'car'
    id = Column(Integer(), primary_key=True)
    info_id = Column(Integer(), ForeignKey('info.id'))
    info = relationship(Info, back_populates='car')

@event.listens_for(Car.info, 'set')
def _car_info_set_event(target, value, oldvalue, initiator):
    if value is not None:
        value.type = 'car'

class Suv(Base):
    __tablename__ = 'suv'
    id = Column(Integer(), primary_key=True)
    info_id = Column(Integer(), ForeignKey('info.id'))
    info = relationship(Info, back_populates='suv')

@event.listens_for(Suv.info, 'set')
def _suv_info_set_event(target, value, oldvalue, initiator):
    if value is not None:
        value.type = 'suv'

事件侦听器的复杂性给您带来的是,当您执行以下操作:

car1.info = Info()
assert (car1.info.type == 'car')

info1 = car1.info
info1.suv = suv1
assert (car1.info is None)
assert (info1.type == 'suv')

如果您想自己保持 Info.type、Info.car 和 Info.suv 一致,则可以省略所有事件侦听器函数。

为 CarInfo 和 SuvInfo 提供单独的对象和表也是一个非常合理的选择,并完全避免所有这些复杂性。

In SQL, a foreign key must be mapped to one specific table, so you need to put the foreign key in the 'car' or 'suv' table pointing to 'info.id'.

This is probably overkill for what you need, but here's one way to solve it (assuming you do in fact want each Car to have only one Info):

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import event
Base = declarative_base()

class Info(Base):
    __tablename__ = 'info'
    id = Column(Integer(), primary_key=True)
    type = Column(String())
    # NOTE: can't use backref='info' because we need the attributes defined
    #   directly on both classes so we can attach event listeners
    car = relationship('Car', back_populates='info', uselist=False)
    suv = relationship('Suv', back_populates='info', uselist=False)

    @property
    def item(self):
        # could check self.type here if you wanted
        return self.car or self.suv

    @item.setter
    def item(self, value):
        if isinstance(value, Car):
            self.car = value
        elif isinstance(value, Suv):
            self.suv = value
        elif value is None:
            self.car = None
            self.suv = None
        else:
            raise ValueError("item must be Car or Suv")

@event.listens_for(Info.car, 'set')
def _car_set_event(target, value, oldvalue, initiator):
    if value is not None:
        target.type = 'car'
        if target.suv:
            target.suv = None
    elif target.type == 'car':
        target.type = None

@event.listens_for(Info.suv, 'set')
def _suv_set_event(target, value, oldvalue, initiator):
    if value is not None:
        target.type = 'suv'
        if target.car:
            target.car = None
    elif target.type == 'suv':
        target.type = None

class Car(Base):
    __tablename__ = 'car'
    id = Column(Integer(), primary_key=True)
    info_id = Column(Integer(), ForeignKey('info.id'))
    info = relationship(Info, back_populates='car')

@event.listens_for(Car.info, 'set')
def _car_info_set_event(target, value, oldvalue, initiator):
    if value is not None:
        value.type = 'car'

class Suv(Base):
    __tablename__ = 'suv'
    id = Column(Integer(), primary_key=True)
    info_id = Column(Integer(), ForeignKey('info.id'))
    info = relationship(Info, back_populates='suv')

@event.listens_for(Suv.info, 'set')
def _suv_info_set_event(target, value, oldvalue, initiator):
    if value is not None:
        value.type = 'suv'

What the complexity of the event listeners gets you is that the type is automatically managed when you do something like:

car1.info = Info()
assert (car1.info.type == 'car')

or

info1 = car1.info
info1.suv = suv1
assert (car1.info is None)
assert (info1.type == 'suv')

If you want to keep Info.type, Info.car, and Info.suv consistent yourself, you can omit all the event listener functions.

It would also be a very reasonable option to have separate objects and tables for CarInfo and SuvInfo, and avoid all this complexity altogether.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文