我希望通过验证用户已经喜欢此帖子的查询来设置我喜欢的不同按钮。如果用户已经喜欢这个,那么按钮将是"不像"和"喜欢"除此以外。我找不到正确的方法来进行查询以及如何在我的模板中实现它。提前谢谢。
我的模特:
class Tweet(models.Model):
added = models.DateTimeField(auto_now_add=True)
tweeter = models.ForeignKey(UserProfile, related_name='user_tweets')
content = models.TextField(max_length=140)
likes = models.IntegerField(default=0)
def __unicode__(self):
return self.content
def total_likes(self):
return self.likes.count()
def approved_comments(self):
return self.comments.filter(approved_comment=True)
class Like(models.Model):
liker = models.ForeignKey(UserProfile, related_name='liked_user')
liked_tweet = models.ForeignKey('Tweet', related_name='liked_post')
liked_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s liked %s tweet' % (self.liker, self.liked_tweet)
答案 0 :(得分:2)
您只需使用要验证的Like
和Tweet
实例查询UserProfile
模型即可。如果存在记录,则用户已经喜欢该推文。
样品:
is_liked = False
try:
Like.objects.get(liked_tweet=tweet, liker=user)
is_liked = True
except Like.DoesNotExist:
pass
答案 1 :(得分:0)
只需在user
表格中检查tweet
和Like
的记录。
like_obj, created = Like.objects.get_or_create(liker=user, liked_tweet=tweet)
if created:
# code for new user liked tweet
else:
# code for record found with user and tweet so unlike tweet by like_obj.delete()