【问题标题】:What's the django way to handle votes on objects?django 处理对象投票的方法是什么?
【发布时间】:2014-11-07 10:04:55
【问题描述】:
class Survey(models.Model):
  answers = models.ManyToMany('Answer')

class Answer(models.Model):
  answer = models.CharField(max_length=30)
  votes = models.IntegerField(default=0)

我想在 html 中显示答案列表及其投票计数,并为每个答案提供一个简单的“+1”按钮,该按钮将增加 votes 的值。

如果我不得不重新发明轮子,我会调用一个视图 upvote(answer_id),它会在数据库中获取答案、增加投票并保存,并且还会在 javascript 中执行相同的操作以更新相应的字段。

在 Django 中有没有更好的方法来做到这一点?

如果在 html 中我允许用户发布新答案,则同样的问题。

【问题讨论】:

  • 你想做什么?服务器端和客户端都更新一次投票?你使用 AJAX 调用还是 http 请求?
  • ajax 调用,更新服务器和客户端的投票

标签: django


【解决方案1】:

您所要做的就是一个带有 JSON 响应的 AJAX 调用。然后用 javascript 更新你的 DOM。

这是一个虚拟示例:

Django 方面:

import json

def upvote(request, anwser_id):
   # You shall write a better test
   a = Answser.objects.get(pk=anwser_id)
   a.votes += 1
   a.save()
   return HttpResponse(json.dumps({
       'count': a.votes,
       'pk': anwser_id
   }, content_type="application/json")

客户站点(假设为 jQuery)- 无需发布:

$.getJSON('/upvote/' + your_anwser_id + '/')
  .done(function(data) {
    // You've got your response here
    $("YOUR-INPUT-SELECTOR").html(data.count);
  })
  .fail(function(xhr) {
    // Server error
    alert("Error: "+ xhr.responseText);
  });

如果有人在两个查询之间投票,您将获得正确的答案。我将这种解决方案用于喜欢/不喜欢 cmets 投票系统。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 2012-07-09
    • 2023-03-15
    • 2010-12-04
    • 1970-01-01
    • 2011-12-19
    • 2011-05-20
    • 2011-06-05
    相关资源
    最近更新 更多