[Python] how to query a flask sqlalcheme tha has two relationship from another single table

Discussão em 'Python' iniciado por Stack, Junho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to query a table that contains userId, which references users, and taggedNameId, which also references users and view it in my template. But i keep getting this error "int object' has no attribute 'users'"

    below is my try

    This is my Model

    class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    fullname = db.Column(db.String(100))
    username = db.Column(db.String(100), unique=True)
    email = db.Column(db.String(100), unique=True)
    gender = db.Column(db.String(100))
    phonenumber = db.Column(db.Integer)
    role = db.Column(db.String(100))
    Password = db.Column(db.String(100))
    datecreated = db.Column(db.DateTime, default=datetime.now)
    notif_user = db.relationship('notifications', foreign_keys="notifications.userId", backref='users')
    tagged_user = db.relationship('notifications', foreign_keys="notifications.taggednameId")


    def __init__(self):
    return self

    class notifications(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.Integer, db.ForeignKey('users.id'))
    content = db.Column(db.String(100))
    taggednameId = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    datecreated= db.Column(db.DateTime, default=datetime.now)


    def __init__(self):
    return self


    This is my Flask-SQLAlchemy Query

    notifications=table.notifications.query.filter(table.notifications.userId==table.Users.id).order_by(table.notifications.datecreated.desc()).all()

    HTML: When I run the code, it says 'int object' has no attribute 'users'. I expect to get the full name of the user who initiated the notification and the full name of the user tagged

    <table class="table table-hover align-middle">
    <thead>
    <tr>
    <th class="fw-bold">SN</th>
    <th class="fw-bold">Name</th>
    <th class="fw-bold">Notifcation_Content</th>
    <th class="fw-bold">Tagged name</th>
    <th class="fw-bold">Date Posted</th>
    </tr>
    </thead>
    <tbody class="table-group-divider">
    {% for N in admindata.notifications %}
    <tr>
    <td>{{loop.index}}</td>
    <td>{{N.users.fullname}}</td>
    <td>{{N.content}}</td>
    <td>{{N.taggednameId.users.fullname}}</td>
    <td>{{N.datecreated}}</td>
    </tr>
    {% endfor %}
    </tbody>
    </table>

    Continue reading...

Compartilhe esta Página