簡體   English   中英

SQLAlchemy多對多,無需外鍵

[英]SQLAlchemy many-to-many without foreign key

有人可以幫我弄清楚我應該如何在缺少一個ForeignKey定義的輔助表上編寫primaryjoin / secondaryjoin。 我不能修改數據庫本身,因為它已被其他應用程序使用。

from sqlalchemy import schema, types, func, orm
from sqlalchemy.dialects.postgresql import ARRAY

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
    __tablename__ = 'atab'
    id = schema.Column(types.SmallInteger, primary_key=True)

class B(Base):
    __tablename__ = 'btab'
    id = schema.Column(types.SmallInteger, primary_key=True)

    a = orm.relationship(
        'A', secondary='abtab', backref=orm.backref('b')
    ) 

class AB(Base):
    __tablename__ = 'abtab'
    id = schema.Column(types.SmallInteger, primary_key=True)
    a_id = schema.Column(types.SmallInteger, schema.ForeignKey('atab.id'))
    b_id = schema.Column(types.SmallInteger)

我試過指定聯接條件上的外國人:

a = orm.relationship(
    'A', secondary='abtab', backref=orm.backref('b'),
    primaryjoin=(id==orm.foreign(AB.b_id))
) 

但是收到以下錯誤:

ArgumentError: Could not locate any simple equality expressions involving locally mapped foreign key columns for primary join condition '"atab".id = "abtab"."a_id"' on relationship Category.projects.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or are annotated in the join condition with the foreign() annotation. To allow comparison operators other than '==', the relationship can be marked as viewonly=True.

您可以將foreign_keys添加到您的關系配置中。 他們在郵件列表中提到了這一點:

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    logon = Column(String(10), primary_key=True)
    group_id = Column(Integer)

class Group(Base):
    __tablename__ = 'groups'
    group_id = Column(Integer, primary_key=True)
    users = relationship('User', backref='group',
        primaryjoin='User.group_id==Group.group_id',
        foreign_keys='User.group_id')

engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

u1 = User(logon='foo')
u2 = User(logon='bar')
g = Group()
g.users = [u1, u2]
session.add(g)
session.commit()
g = session.query(Group).first()
print([user.logon for user in g.users])

輸出:

['foo', 'bar']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM