我正在使用 Postgresql 和 FlaskSqlalchemy 。我想創建一個關系,這樣一個團隊可以有多個頻道,但一個頻道只能有一個團隊(一對多關系)。我試圖通過一對多的關系來做到這一點,如下所示我在models.py中有以下代碼
class Team(db.Model):
__tablename__ = "team"
id = db.Column(db.Integer, primary_key=True)
team_owner_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
team_name = db.Column(db.String(50), nullable=False, unique=True)
team_logo = db.Column(db.String(120), default='default.png')
team_description = db.Column(db.String(110), default="Welcome to My team.....")
team_members = db.Column(MutableDict.as_mutable(JSON))
team_members_count = db.Column(db.Integer)
channel_list = db.relationship("Channel", backref="list", lazy=True)
class Channel(db.Model):
channel_id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey("team.id"), nullable=False)
channel_name = db.Column(db.String(50), nullable=False, unique=True)
channel_logo = db.Column(db.String(120), default='default.jpg')
channel_description = db.Column(db.String(110), default="Welcome to My Channel.....")
channel_members = db.Column(MutableDict.as_mutable(JSON))
channel_members_count = db.Column(db.Integer)
我可以創建一個團隊,但是當我嘗試創建一個頻道時,除了關系部分之外,一切都很好。我試圖通過執行使 channels_list(backref='list') 成為串列
list = []
更多代碼如下
channel = Channel(channel_name=form.channel_name.data, channel_description =
form.channel_description.data , channel_members = {'member_id': [] , 'name' : []},
channel_members_count=channel_members_count, list = []
)
channel.list.append(form.channel_name.data)
db.session.add(channel)
db.session.commit()
注意:我沒有添加一些與此錯誤無關的代碼,例如填充 channel_members 以避免浪費您的時間現在當我嘗試創建頻道時出現錯誤:
AttributeError: 'dict' object has no attribute '_sa_instance_state'
TraceBack:[https://i.stack.imgur.com/2XHnl.png[1] 我在哪里犯了錯誤,或者甚至可以在具有一對多關系的同時存盤串列。如果我可以在保持這種關系的同時存盤一個 JSON 物件,那將是最好的。感謝您的指導
uj5u.com熱心網友回復:
因此,“backref”的意思是它對與給定頻道關聯的父“團隊”的“反向參考”。
因此,例如,如果您在資料庫中有一個名為“team_a”的現有團隊,并且您想創建一個與該“team_a”相關聯的新頻道。以下是你的做法:
new_channel = Channel(channel_info)
# find team with name "team_a"
team = Team.query.filter_by(name="team_a").first()
# associate this team with the new_channel using the backref to the team
# which is called "list"
new_channel.list = team
db.session.add(new_channel)
db.session.commit()
Channel.list不是串列,它是對與給定頻道相關的團隊物件的參考。因此,當您創建新頻道時,您應該使用它將頻道與團隊相關聯。這樣,頻道將被索引為父團隊的孩子(或“許多”)的一部分。由于團隊 -> 頻道存在一對多。
這使得我們可以使用“team”物件上的“channel_list”屬性獲取與團隊關聯的所有頻道。您不需要直接在團隊物件上附加它,只要您在創建團隊時已將團隊與頻道相關聯。
我建議您將 backref 命名為“teams”表上不太容易混淆的名稱,例如“team”或“parent_team”。像這樣:
channel_list = db.relationship("Channel", backref="team", lazy=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483706.html
標籤:Python 烧瓶 烧瓶-sqlalchemy 一对多 psql
