Skip to content

Instantly share code, notes, and snippets.

@pramodvspk
Created March 25, 2017 17:41
Show Gist options
  • Save pramodvspk/c3909872c7d6d424d3c6e9e70550f319 to your computer and use it in GitHub Desktop.
Save pramodvspk/c3909872c7d6d424d3c6e9e70550f319 to your computer and use it in GitHub Desktop.
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
description = models.CharField(max_length=1000)
image = models.ImageField(null=True)
'''
https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/
https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects
http://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django
'''
likes = models.ManyToManyField(User, through='PostComments', related_name="likes")
shares = models.ManyToManyField(User, through='PostShares', related_name="shares")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def get_comment_count(self):
return len(self.postcomments_set)
def get_share_count(self):
return len(self.postshares_set)
def __str__(self):
return self.description
class PostShares(models.Model):
sharing_user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class PostLikes(models.Model):
liking_user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
'''
My View Starts
'''
def like_status(request):
if request.method == "POST":
post_id = request.POST.get('post_id')
user = request.user
post = get_object_or_404(Post, pk=post_id)
post_likes = PostLikes(liking_user=user, post=post)
How should I check if the like is already there and then remove it or add it
'''
if post.likes.filter(id=user.id).exists():
post.likes.remove(user)
message = "You unliked this"
else:
post.likes.add(user)
message = "You liked this"
'''
ctx = {'likes_count': 10, 'message': message}
return HttpResponse(json.dumps(ctx), content_type='application/json')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment