2
我使用兩個表的Flask + SQLAlchemy + PostgreSQL。 包含用戶的表格和包含目標的表格(用戶想要實現的內容)。SQLAlchemy + Flask多對一的關係
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' object has no attribute 'append'
事實上,我錯過了uselist =假的地步。所以現在很好。但關於這種關係。你確定嗎 ? 「我基於http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html上的關係定義(請參閱:多對一,雙向行爲..) –
啊是的,我的錯誤我習慣於使用' backref'而不是'back_populates'。我會更新我的答案 – pech0rin