我使用带有两个表的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'
答案 0 :(得分:1)
您将目标定义为uselist=False
,这意味着它不会存储为数组。您只需要user.goal = goal
代替append
,因为它不会存储为列表。
所以而不是
user = User()
goal = Goal()
user.goal.append(goal)
这样做:
user.goal = goal