gpt4 book ai didi

python - 如何从模板调用模型函数?

转载 作者:行者123 更新时间:2023-12-01 09:15:10 25 4
gpt4 key购买 nike

我正在从模板调用我的模型(Answer)函数isupvoted,同时迭代页面上显示的所有答案,以查看登录用户是否喜欢迭代回答。我的AnswerUpvote模型如下。

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 没有返回任何内容。如何获得点赞数?

最佳答案

在您的模型中,使用@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

关于python - 如何从模板调用模型函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51341625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com