Reputation: 1755
I have a Django Rest Framework project, users can post,comment any post and like any post. I can't figure it out the logic in models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.CharField(max_length=100)
post_author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='posts')
def __str__(self):
return self.title
class Comment(models.Model):
body=models.CharField(max_length=100)
commet_post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
comment_author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.body
class Like(models.Model):
like_post = models.ForeignKey(Post,on_delete=models.CASCADE)
like_author=models.ForeignKey(User,on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
Upvotes: 0
Views: 872
Reputation: 634
You could make two endpoints for like: 1) for create & 2) for delete. Whenever someone clicks on the like button, it will hit the create endpoint and create a Like object. When someone clicks on unlike, it will hit the delete endpoint and delete the object. Like model will have a one-to-one relationship with User and Post model. You can count likes by a query such as: Like.objects.filter(like_post=post.id).aggregate(Count('pk'))
Upvotes: 1