【问题标题】:SQLAlchemy+Flask Many to one relationshipSQLAlchemy+Flask 多对一关系
【发布时间】:2016-06-15 15:40:28
【问题描述】:

我正在使用 Flask + SQLAlchemy + PostgreSQL 和两个表。 包含用户的表格和包含目标(用户想要实现的目标)的表格。

models.py:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    user_name = Column(Text)
    email = Column(String(255), unique=True, nullable=False)
    password = Column(String(255))
    # A user can only have one goal at a time
    goal_id = Column(Integer, ForeignKey('goals.id'))
    goal = relationship("Goal", back_populates="user")

class Goal(Base):
    """ Goals: Health, Fitness, Wealth, etc. """
    __tablename__ = 'goals'
    id = Column(Integer(), primary_key=True)
    name = Column(String(80), unique=True)
    description = Column(String(255))
    user = relationship("User", back_populates="goal", uselist=False)

用户一次只能有一个目标。在我的测试用例中,我首先使用以下内容填充表目标:

tests.py:

for goal in ["Health", "Fitness", "Wealth"]:
    session.add(Goal(name=goal))

然后我希望能够填充 3 个用户,每个用户都有不同的目标。实现这一目标的正确方法是什么?

尝试(简化代码):

user = User()
goal = Goal()
user.goal.append(goal)

给我:

  user.goal.append(goal)

E AttributeError: 'NoneType' 对象没有属性 'append'

【问题讨论】:

    标签: flask sqlalchemy


    【解决方案1】:

    您将目标定义为uselist=False,这意味着它没有被存储为数组。您只需要使用user.goal = goal 而不是append,因为它没有存储为列表。

    所以不是

    user = User()
    goal = Goal()
    user.goal.append(goal)
    

    这样做:

    user.goal = goal
    

    【讨论】:

    • 确实我错过了 uselist=False 的要点。所以现在好了。不过关于关系。您确定吗 ? `我的关系定义基于docs.sqlalchemy.org/en/latest/orm/basic_relationships.html(参见:多对一,双向行为..)
    • 啊,是的,我的错误是我习惯使用backref 而不是back_populates。我会更新我的答案
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多