我正在从模板调用我的模型(Answer
)函数isupvoted
,同时遍历页面上显示的所有答案,以查看登录用户是否喜欢该迭代答案。我的Answer
和Upvote
模型如下。
class Answer(models.Model):
answer_text = models.TextField(max_length=5000)
answer_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ans_auth')
question = models.ForeignKey(Question, on_delete=models.CASCADE)
a_pub_date = models.DateTimeField('Date Answer Published')
a_modified_date = models.DateTimeField('Date Answer Modified', null=True, blank=True)
def __str__(self):
return self.answer_text
def isupvoted(self, request):
counter = UpvoteAnswerMod.objects.filter(answer=self, upvote_user=request.user).count()
print("upvote count: "+counter)
return counter
class UpvoteAnswerMod(models.Model):
answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
upvote_user = models.ForeignKey(User, on_delete=models.CASCADE)
upvote_date = models.DateTimeField('Date Upvoted')
我正在调用以下函数
{% if answer.isupvoted == 1 %}
<a class="upvote pressed" href="#" >Downvote</a>
{% else %}
<a class="upvote" href="#" >Upvote</a>
{% endif %}
但是answer.isupvoted
没有返回任何内容。我如何获得投票数?
答案 0 :(得分:1)
在模型中,使用@property
:
@property
def isupvoted(self, user):
try:
counter = UpvoteAnswerMod.objects.filter(answer=self,
upvote_user=user).count()
print("upvote count: "+counter)
return counter
except ObjectDoesNotExist as e:
print("Not Found - {}".format(e))
return 0