I have a User
table
I have a Post
table
Users can vote posts, here I use a UserVotesPost
table which is a many to many relation.
Here is the code:
class UserVotesPost(Base):
__tablename__ = 'uservotesposts'
user_id = Column(Integer, ForeignKey('users.id'), primary_key=True)
post_id = Column(Integer, ForeignKey('posts.id'), primary_key=True)
likes_post = Column(Boolean, nullable=False)
date_added = Column(DateTime, nullable=False)
child = relationship("Post")
class User(UserMixin, Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(Text, nullable=False, unique=True)
password = Column(Text, nullable=False)
children_UserVotesPost = relationship("UserVotesPost")
# etc ...
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
title = Column(Text, nullable=False)
description = Column(Text, nullable=True)
created_on = Column(DateTime, nullable=False)
updated_on = Column(DateTime, nullable=False)
views = Column(Integer, nullable=False, default=0)
visible_to_tier_id = Column(Integer, nullable=True)
hidden_post = Column(Boolean, nullable=False, default=False)
# etc ...
Adding data works fine, but now I want to display the data in view by using the relation & correct syntax.
What I want exactly is to display the total amount of likes and dislikes for a certain post in view.
My ideas so far:
I could simply query all UserVotesPost
and create nested for ... if
loops in view to compare and count the posts. That would look something like that:
all_votes = UserVotesPost.query.all()
all_posts = Post.query.all()
In view:
{% for post in all_posts %}
{% for vote in all votes %}
{% if post.id == vote.post_id %}
{% if vote.likes_post == True %}
# increase count for likes true
{% else %}
# increase count for likes false
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
But this is a complete workaround, which does not use the DB relations and is probably very bad for performance. But it would work.
I am currently playing around with the relation, but so far I only managed to get all user likes/dislikes by using the relation:
for vote in current_user.children_UserVotesPost:
print (vote.likes_post)