Hi, this is my first time implementing a like system in my project. Below is my implementation, which I developed using various sources: tips from chat rooms and AI. But since I have no experience with this, I would like to learn best practices for implementing a like chip that is used in work projects. After all, my implementation seems a bit crude to me.
My model ‘Like’ and relation with model ‘Recipe’
class Like(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["user", "recipe"], name="unique_user_recipe"
)
]
liked_users = models.ManyToManyField(get_user_model(), through="Like", related_name="liked_recipes", blank=True)
view
class LikeToggleAPIView(APIView):
permission_classes = [IsAuthenticated]
def post(self, request, slug):
user = request.user
recipe = get_object_or_404(Recipe, slug=slug)
like_obj = Like.objects.filter(user=user, recipe=recipe).first()
if like_obj:
like_obj.delete()
is_liked = False
else:
Like.objects.create(user=user, recipe=recipe)
is_liked = True
return Response({"is_liked": is_liked, "like_count": recipe.liked_users.count()}, status=status.HTTP_200_OK)
I would be happy to hear your advice!