python - SqlAlchemy。无法添加两个外键。有多个外键路径链接表

标签 python sqlalchemy

我是 sqlalchemy 的新手。我需要在子(学生)类(class)中创建两个外键。
现在我可以做这样的事情:

>>> student_one = Student(name='Sam')
>>> student_two = Student(name='Nick')
>>> group_one = Group(group_number='ST141', students=[student_one, student_two], senior_student=student_one)
>>> group_one.students
>>> group_one.senior_student

这是正确的。现在我想在 Student 表中有 senior_student_of 字段。我尝试了很多方法来执行某些操作,但无法添加它。 这是我的代码:

class Group(Base):
    __tablename__ = 'groups'
    id = Column(Integer, primary_key=True)
    group_number = Column(String(10), nullable=True, default='')
    study_hours = Column(Integer, default=0, nullable=True)
    lab_studies = Column(Integer, default=0, nullable=True)
    pract_studies = Column(Integer, default=0, nullable=True)

    curator = relationship('Tutor', backref='tutors', lazy='dynamic')
    students = relationship('Student', backref='groups', lazy='dynamic')
    senior_student = relationship('Student', uselist=False, lazy='joined')

    def __repr__(self):
        return self.group_number


class Student(Base):
    __tablename__ = 'students'
    id = Column(Integer, primary_key=True)
    surname = Column(String(20), nullable=True, default='', )
    name = Column(String(20), nullable=True, default='')
    patronymic = Column(String(20), nullable=True, default='')
    absences = Column(Integer, nullable=True, default=0)
    undone_labs = Column(Integer, nullable=True, default=0)
    unready_labs = Column(Integer, nullable=True, default=0)

    group_id = Column(Integer, ForeignKey(Group.id))
    group = relationship(Group)

    # This don't work
    senior_student_of_id = Column(Integer, ForeignKey(Group.id))
    senior_student_of = relationship(Group)

总是出现错误:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Group.students - there are multiple foreign key paths linking the tables.  Specify the 'f
oreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

最后,我需要正确获取 student_one.senior_student_of 并在那里查看 ST141
无法搜索正确的解决方案。谢谢你的帮助! :)

最佳答案

你可以这样做:

group = relationship(Group, foreign_keys=[group_id, ])
senior_student_of = relationship(Group, foreign_keys=[senior_student_of_id, ])

同时从组中删除关系定义。使用 backref 定义 backref,如下所示:

    class Group(Base):
        __tablename__ = 'groups'
        id = Column(Integer, primary_key=True)
        group_number = Column(String(10), nullable=True, default='')
        study_hours = Column(Integer, default=0, nullable=True)
        lab_studies = Column(Integer, default=0, nullable=True)
        pract_studies = Column(Integer, default=0, nullable=True)

        def __repr__(self):
            return self.group_number


    class Student(Base):
        __tablename__ = 'students'
        id = Column(Integer, primary_key=True)
        surname = Column(String(20), nullable=True, default='', )
        name = Column(String(20), nullable=True, default='')
        patronymic = Column(String(20), nullable=True, default='')
        absences = Column(Integer, nullable=True, default=0)
        undone_labs = Column(Integer, nullable=True, default=0)
        unready_labs = Column(Integer, nullable=True, default=0)

        group_id = Column(Integer, ForeignKey(Group.id))
        group = relationship(Group, foreign_keys=[group_id, ], backref="students")

        senior_student_of_id = Column(Integer, ForeignKey(Group.id), backref="senior_student")
        senior_student_of = relationship(Group, foreign_keys=[senior_student_of_id, ])

我从未使用过 uselist=False ,所以我不知道它是否有效。

我不确定这是否是您的真正意思:

students = relationship('Student', backref='groups', lazy='dynamic')

这会将 backref 组放入 Student,这意味着您将拥有 Student.group。但您还在 Student 类中定义了 Student.group。

关于python - SqlAlchemy。无法添加两个外键。有多个外键路径链接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59012315/

相关文章:

Python从tcp套接字解包二进制流

python - 如何使用 alembic/SQLAlchemy 将表对象实例化为 bulk_insert 行

python - 为什么struct中第一个打包的数据是little endian,而其余的都是big endian?

python - 如何使用多处理 python 更新和检索图像?

python - 语法错误 : Non-UTF-8 code starting with '\x82'

python - 添加到列表中的项目未按预期顺序排列

python - 通过 'relationship' 中定义的链接对结果进行排序

python - SQLAlchemy:使用 ORM 扫描大表?

python - 通过声明性映射创建架构 : Base.metadata.create_all(engine) 不起作用

python - 是否可以将 plotly 表保存为 png?