Python sqlalchemy:与声明式的一对一关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3464443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:12:48  来源:igfitidea点击:

sqlalchemy: one-to-one relationship with declarative

pythonsqlalchemy

提问by carl

What is the best way to create a one-to-one relationship in SQLAlchemy using declarative?

使用声明性在 SQLAlchemy 中创建一对一关系的最佳方法是什么?

I have two tables, fooand bar, and I want foo.bar_idto link to bar. The catch is that this is a one-way one-to-one relationship. barmust not know anything about foo. For every foo, there will be one and only one bar.

我有两个表foobar,我想foo.bar_id链接到bar. 问题在于,这是一种单向的一对一关系。bar一定一无所知foo。对于每个 foo ,都会有一个并且只有一个bar

Ideally, after selecting a foo, I could do something like this:

理想情况下,选择 foo 后,我可以执行以下操作:

myfoo.bar.whatever = 5 

What's the best way to accomplish this using declarative?

使用声明性完成此任务的最佳方法是什么?

采纳答案by Brett Bim

If you want a true one-to-one relationship, you also have to use the "uselist=False" in your relationship definition.

如果您想要真正的一对一关系,您还必须在关系定义中使用“uselist=False”。

bar_id = Column(Integer, ForeignKey(Bar.id))
bar = relationship(Bar, uselist=False)

回答by carl

It turns out this is actually quite easy. In your Foo model:

事实证明,这实际上很容易。在您的 Foo 模型中:

bar_id = Column(Integer, ForeignKey(Bar.id))
bar = relationship(Bar)

回答by chadwick.boulay

The documentation explains this nicely:

文档很好地解释了这一点

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child = relationship("Child", uselist=False, backref="parent")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))

OR

或者

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref=backref("parent", uselist=False))

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

回答by hamidfzm

I think if it is a truly one to one relationship we should add a uniqueness constraint to foreign key so another parent can not have other parent child!! Like this:

我认为如果它是真正的一对一关系,我们应该为外键添加唯一性约束,这样另一个父级就不能有另一个父级子级!!像这样:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'), unique=True)
    child = relationship("Child", backref=backref("parent", uselist=False))

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)