Adding the Like Feature
Learn to implement the like feature functionality in our application.
A nice feature to have in a social media application is liking. Like Facebook, Instagram, or Twitter, we’ll allow users here to like a post.
We’ll also add data to count the number of likes a post has received and check whether a current user making the request has liked a post.
We’ll do this in four steps:
Add a new
posts_liked
field to theUser
model.Write methods on the
User
model to like and remove a like from a post. We’ll also add a method to check whether the user has liked a post.Add
likes_count
andhas_liked
toPostSerializer
.Add endpoints to like a post and remove a like from a post.
Great! Let’s start by adding the new fields to the User
model.
Adding the posts_liked
field to the User
model
The posts_liked
field will contain all the posts liked by a user. The relationship between the User
model and the Post
model concerning the “Like” feature can be described as follows:
A user can like many posts.
A post can be liked by many users.
Does this kind of relationship sound familiar? It is a many-to-many relationship.
Following this change, here’s the updated structure of the table—we are also anticipating the methods we’ll add to the model:
Get hands-on with 1200+ tech skills courses.