Creating a Table for Post Likes

To allow users to like or dislike posts in your social media application, you’ll need to create a separate table to store these interactions. This table will typically have a foreign key referencing the user and the post involved.

Creating the PostLikes Table

Python

from sqlalchemy import Column, Integer, ForeignKey

class PostLike(Base):
    __tablename__ = "post_likes"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))   
    post_id = Column(Integer, ForeignKey("posts.id"))

    user = relationship("User", back_populates="liked_posts")
    post = relationship("Post", back_populates="likes")   

Explanation:

  • The PostLike model represents a like or dislike interaction between a user and a post.
  • The user_id and post_id columns reference the corresponding User and Post records.
  • The relationship statements define the relationships between the PostLike model and the User and Post models.

Creating Endpoints for Liking and Disliking Posts

Python

@router.post("/posts/{post_id}/like")
async def like_post(post_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    # Check if the user has already liked or disliked the post
    existing_like = await db.query(PostLike).filter(PostLike.user_id == current_user.id, PostLike.post_id == post_id).first()
    if existing_like:
        return {"message": "You have already liked or disliked this post"}

    # Create a new like
    like = PostLike(user_id=current_user.id, post_id=post_id)
    db.add(like)
    await db.commit()
    await db.refresh(like)
    return {"message": "Post liked"}

@router.delete("/posts/{post_id}/like")
async def unlike_post(post_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    # Find the existing like
    existing_like = await db.query(PostLike).filter(PostLike.user_id == current_user.id, PostLike.post_id == post_id).first()
    if not existing_like:
        return {"message": "You have not liked or disliked this post"}

    # Delete the like
    db.delete(existing_like)
    await db.commit()
    return {"message": "Post unliked"}

Retrieving Post Likes

Python

@router.get("/posts/{post_id}/likes")
async def get_post_likes(post_id: int, db: Session = Depends(get_db)):
    likes = await db.query(PostLike).filter(PostLike.post_id == post_id).all()
    return likes

By following these steps, you can effectively implement post liking functionality in your FastAPI application, allowing users to interact with and engage with the content on your platform.

Adding API Routes for Liking Posts
Writing Tests for File Uploads

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?