0
我正在開發一個Django項目,用戶可以詢問並回答問題。與此同時用戶可以投票答案像stackoverflow答案。現在我想鏈接用戶的答案和投票的投票數字。例如用戶A回答了一個問題,他的答案得到了10票,用戶A又回答了另一個問題並得到5票。現在這個用戶的投票應該是15. 我該怎麼做?有任何想法嗎? 在此先感謝。 這是我的模型:如何鏈接用戶投票的答案投票?
class Answer(models.Model):
user = models.ForeignKey(msignup, related_name="uanswer")
question = models.ForeignKey(Question)
description = models.TextField(max_length=2000)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True, auto_now_add=False)
votes = models.IntegerField(default=0)
is_accepted = models.BooleanField(default=False)
upload = models.FileField(upload_to=upload_location, null=True, blank=True)
class Meta:
verbose_name = 'Answer'
verbose_name_plural = 'Answers'
ordering = ('-is_accepted', '-votes', 'create_date',)
def __str__(self):
return self.description
def accept(self):
answers = Answer.objects.filter(question=self.question)
for answer in answers:
answer.is_accepted = False
answer.save()
self.is_accepted = True
self.save()
self.question.has_accepted_answer = True
self.question.save()
def calculate_votes(self):
up_votes = Activity.objects.filter(activity_type=Activity.UP_VOTE,
answer=self.pk).count()
down_votes = Activity.objects.filter(activity_type=Activity.DOWN_VOTE,
answer=self.pk).count()
self.votes = up_votes - down_votes
self.save()
return self.votes
,這是我的看法:
def vote(request):
answer_id = request.POST['answer']
answer = Answer.objects.get(pk=answer_id)
vote = request.POST['vote']
userID = request.session.get('mainSession', 0)
user = msignup.objects.get(id=userID)
activity = Activity.objects.filter(
Q(activity_type=Activity.UP_VOTE) | Q(activity_type=Activity.DOWN_VOTE),
user=user, answer=answer_id)
if activity:
activity.delete()
if vote in [Activity.UP_VOTE, Activity.DOWN_VOTE]:
activity = Activity(activity_type=vote, user=user, answer=answer_id)
activity.save()
return HttpResponse(answer.calculate_votes())
您是否閱讀過[聚合主題指南](https://docs.djangoproject.com/en/1.11/topics/db/aggregation/)?提示:總結用戶提供的所有答案的選票。 – Melvyn
謝謝。但我想爲用戶得到的所有答案總結選票。例如他的答案之一得到10,而另一個得到5,現在用戶有15票,並可以顯示在用戶配置文件部分。 –
看@ darthvader1996的答案。這就是我所說的,只有他拼寫出來。 – Melvyn