Python 对具有相同 ID 的项目进行循环
Python for loop for items with the same id
我对 Python 还是很陌生,我正在努力学习。我尝试寻找类似的问题,但找不到问题的答案。基本上,我有一个 psql 数据表,其中有 3 列,如下图所示,其中一列是文本列,用于保存人们留下的评论,其中一列是每个评论的 ID,最后一列是 ID他们链接到哪个帐户。我的问题是,我如何打印所有 msr.id 等于 72 的文本,知道有多个 msr_id 等于 72 的文本(我如何打印一个用户的所有评论谁的 msr_id 等于 72)?这是我的 Python 代码:
class Commentaire(db.Model):
__tablename__ = "commentaire"
msr_id = db.Column(db.Integer)
text = db.Column(db.Text())
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
def __init__(self, text, msr_id):
self.text = text
self.msr_id = msr_id
@app.route("/msr/<int:item_id>/history")
@require_privilege()
@templated("MSR/history.htm")
def msr_history(item_id=None):
msr = MSR.query.get(item_id)
commentaire = Commentaire.query.get(item_id) <--- this is the table in my database
print(msr.pos)
while (commentaire.id < 74):
if (commentaire.msr_id == 72):
print(commentaire.text)
commentaire.id += 1
if msr is None:
return abort(404)
return {"msr": msr, "first_pos": str(), "commentaire": commentaire}
您必须使用 if
而不是 while
,因为您只想打印 ID 为 72 的评论。
def msr_history(item_id=None):
msr = MSR.query.get(item_id)
commentaire = Commentaire.query.get(item_id) database
print(msr.pos)
# Not sure if it works. I am assuming commentaire returns a queryset.
for item in commentaire:
if (item.msr_id == 72)
print(commentaire.text)
if msr is None:
return abort(404)
return {"msr": msr, "first_pos": str(), "commentaire": commentaire}
我对 Python 还是很陌生,我正在努力学习。我尝试寻找类似的问题,但找不到问题的答案。基本上,我有一个 psql 数据表,其中有 3 列,如下图所示,其中一列是文本列,用于保存人们留下的评论,其中一列是每个评论的 ID,最后一列是 ID他们链接到哪个帐户。我的问题是,我如何打印所有 msr.id 等于 72 的文本,知道有多个 msr_id 等于 72 的文本(我如何打印一个用户的所有评论谁的 msr_id 等于 72)?这是我的 Python 代码:
class Commentaire(db.Model):
__tablename__ = "commentaire"
msr_id = db.Column(db.Integer)
text = db.Column(db.Text())
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
def __init__(self, text, msr_id):
self.text = text
self.msr_id = msr_id
@app.route("/msr/<int:item_id>/history")
@require_privilege()
@templated("MSR/history.htm")
def msr_history(item_id=None):
msr = MSR.query.get(item_id)
commentaire = Commentaire.query.get(item_id) <--- this is the table in my database
print(msr.pos)
while (commentaire.id < 74):
if (commentaire.msr_id == 72):
print(commentaire.text)
commentaire.id += 1
if msr is None:
return abort(404)
return {"msr": msr, "first_pos": str(), "commentaire": commentaire}
您必须使用 if
而不是 while
,因为您只想打印 ID 为 72 的评论。
def msr_history(item_id=None):
msr = MSR.query.get(item_id)
commentaire = Commentaire.query.get(item_id) database
print(msr.pos)
# Not sure if it works. I am assuming commentaire returns a queryset.
for item in commentaire:
if (item.msr_id == 72)
print(commentaire.text)
if msr is None:
return abort(404)
return {"msr": msr, "first_pos": str(), "commentaire": commentaire}