SqlAlchemy count table relationships

Viewed 65

I have a class users here that can like and unlike posts made by other users. I have a table to keep track of the likes and dislikes from users to the posts like so:

class Users(db.Model):
    id = db.Column("id", db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    email = db.Column(db.String(100))
    password = db.Column(db.String(100))
    status = db.Column(db.String(100))
    about = db.Column(db.String(500))
    liked = db.relationship(
        'PostLike',
        foreign_keys='PostLike.user_id',
        backref='user', lazy='dynamic')

    def like_post(self, post):
        if not self.has_liked_post(post):
            like = PostLike(user_id=self.id, post_id=post.id)
            db.session.add(like)

    def unlike_post(self, post):
        if self.has_liked_post(post):
            PostLike.query.filter_by(
                user_id=self.id,
                post_id=post.id).delete()

    def has_liked_post(self, post):
        return PostLike.query.filter(
            PostLike.user_id == self.id,
            PostLike.problem_id == post.id).count() > 0

    def __init__(self, name, email, password, status):
        self.name = name
        self.email = email
        self.password = password
        self.status = status
        self.about = "Nothing so far..."
        self.liked_posts = ""


class Problem(db.Model):
    id = db.Column("id", db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    contents = db.Column(db.String(700))
    author_id = db.Column(db.Integer)
    time = db.Column(db.DateTime)

    def __init__(self, title, contents, author_id):
        self.title = title
        self.contents = contents
        self.author_id = author_id
        self.time = datetime.now()


class PostLike(db.Model):
    __tablename__ = 'post_like'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    problem_id = db.Column(db.Integer, db.ForeignKey('problem.id'))

Some code is from this stack post: How do i implement a like button function to posts in Python Flask?

Now what I want to do is to count the number of likes given post has through the database. I looked at this: Counting relationships in SQLAlchemy but I don't know what func and core means so does anyone have a solution I can use?

0 Answers
Related