matthew fabrie
matthew fabrie

Reputation: 103

Python for loop for items with the same id

I am still very new to Python and I am trying to learn. I tried looking for a similar question but I was unable to find an answer to my question. Basicaly, I have a psql datatable with 3 columns in it as shown on the picture down below, one of the columns is a text column which saves comments people left, one of them is the id of each comment and the last one is the id of which account they are linked to. My question is, how can i print all of the texts that have msr.id equal to 72 knowing that there are multiple texts with msr_id equal to 72 (how can i print all of the comments of one single user who's msr_id is equal to 72)? Here's my Python code:

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}

enter image description here

Upvotes: 0

Views: 354

Answers (1)

Ram
Ram

Reputation: 4779

You have to use an if and not a while since you want to print only the comments that has 72 as id.

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}

Upvotes: 1

Related Questions