Issue
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
likedComments = db.relationship('Comment', secondary=user_likedComment, backref='likedby')
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_likedComment = db.Table('user_likedComment',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('comment_id', db.Integer, db.ForeignKey('comment.id'))
)
When I create this many-to-many relationship, accessing comment.likedby gives me a list of [<User "id">, ...]. This is a problem because when I try to compare a member of this list to a user.id it does not ever find it because it compares "<User "id">" to a single integer(user.id). How can I only get the id and not the class name or <> from the list. It's hard for me because I am accessing this list in html and can only iterate it through Jinja, and cannot use python. In html with Jinja:
{% for cmt in forum.comments %}
create comment
{% for userId in cmt.likedby %}
{% if user.id == userId %}
check if user is in likedby list (never works because it compares integer "id" to "<User "id">")
{% endif %}
{% endfor %}
{% endfor %}
Normally, I would've sliced or index but cannot use that because it is in html, so i cannot use python. The list also cannot be used in javascript because it is from python.
Solution
cmt.likedby
is a list of objects of type User
.
So when you iterate through this list you should get id
attribute of these objects:
{% for cmt in forum.comments %}
create comment
{% for user_who_liked in cmt.likedby %}
{% if user.id == user_who_liked.id %}
Something...
{% endif %}
{% endfor %}
{% endfor %}
Answered By - Yurii Motov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.