使用 django 进行 Reddit 风格投票

发布于 2024-09-03 08:45:21 字数 2300 浏览 0 评论 0原文

我需要将投票系统手动实现到模型中。

迈克·德西蒙 (Mike DeSimone) 为我的工作提供了巨大的帮助,但我需要扩展他的工作。

这是我当前的代码

View

def show_game(request):
    game = Game.objects.get(pk=1)
    discussions = game.gamediscussion_set.filter(reply_to=None)
    d = {
        'game':game,
        'discussions':discussions
    }
    return render_to_response('show_game', d)

Template

<ul>
    {% for discussion in discussions %}
    {{ discussion.html }}
    {% endfor %}
</ul>

Model

class GameDiscussion(models.Model):
    game = models.ForeignKey(Game)
    message = models.TextField()
    reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True)
    created_on = models.DateTimeField(blank=True, auto_now_add=True)
    userUpVotes = models.ManyToManyField(User, blank=True, related_name='threadUpVotes')
    userDownVotes = models.ManyToManyField(User, blank=True, related_name='threadDownVotes')

    def html(self):
        DiscussionTemplate = loader.get_template("inclusions/discussionTemplate")
        return DiscussionTemplate.render(Context({
            'discussion': self,
            'replies': [reply.html() for reply in self.replies.all()]
    }))

DiscussionTemplate

<li>
    {{ discussion.message }}
    {% if replies %}
        <ul>
            {% for reply in replies %}
                {{ reply }}
            {% endfor %}
        </ul>
    {% endif %}
</li>

如您所见,我们有 2 个字段 userUpVotes 和 userDownVotes模型,这些将计算如何排序讨论和回复。

我将如何实现这两个字段来根据投票排序回复和讨论?

任何帮助都会很棒!

编辑

我在我的模型中添加了一个名为 vote_difference 的方法,

    def vote_difference(self):
        return int(self.userUpVotes.count()) - int(self.userDownVotes.count())

我可以在模板中使用它来获取当前投票,但是我无法在我的 view.py 文件中使用它来按此值排序,是无论如何,我认为要包含这个值吗?

编辑(2)

我已经慢慢到达那里,我需要注释2个字段并对它们进行计算,但是似乎我无法使用注释进行基本数学计算。

有什么想法吗?

    discussions = game.gamediscussion_set.filter(reply_to=None).annotate( score= (Count('userUpVotes') - Count('userDownVotes')) ).order_by('-score')

Hay i need to hand implemeneting a voting system into a model.

I've had a huge helping hand from Mike DeSimone making this work in the first place, but i need to expand upon his work.

Here is my current code

View

def show_game(request):
    game = Game.objects.get(pk=1)
    discussions = game.gamediscussion_set.filter(reply_to=None)
    d = {
        'game':game,
        'discussions':discussions
    }
    return render_to_response('show_game', d)

Template

<ul>
    {% for discussion in discussions %}
    {{ discussion.html }}
    {% endfor %}
</ul>

Model

class GameDiscussion(models.Model):
    game = models.ForeignKey(Game)
    message = models.TextField()
    reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True)
    created_on = models.DateTimeField(blank=True, auto_now_add=True)
    userUpVotes = models.ManyToManyField(User, blank=True, related_name='threadUpVotes')
    userDownVotes = models.ManyToManyField(User, blank=True, related_name='threadDownVotes')

    def html(self):
        DiscussionTemplate = loader.get_template("inclusions/discussionTemplate")
        return DiscussionTemplate.render(Context({
            'discussion': self,
            'replies': [reply.html() for reply in self.replies.all()]
    }))

DiscussionTemplate

<li>
    {{ discussion.message }}
    {% if replies %}
        <ul>
            {% for reply in replies %}
                {{ reply }}
            {% endfor %}
        </ul>
    {% endif %}
</li>

As you can see we have 2 fields userUpVotes and userDownVotes on the model, these will calculate how to order the discussions and replies.

How would i implement these 2 fields to order the replies and discussions based on votes?

Any help would be great!

EDIT

I've added a method to my model called vote_difference

    def vote_difference(self):
        return int(self.userUpVotes.count()) - int(self.userDownVotes.count())

I can user this in my templates to get the current vote, however i cannot use this in my view.py file to order by this value, is there anyway to include this value in my view?

EDIT (2)

I've slowly getting there, i need to annotate 2 fields and do a calculation on them, however it seems that i cannot do basic maths calculation with annotate.

Any ideas?

    discussions = game.gamediscussion_set.filter(reply_to=None).annotate( score= (Count('userUpVotes') - Count('userDownVotes')) ).order_by('-score')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一笔一画续写前缘 2024-09-10 08:45:21

您可能需要考虑通过添加 vote_score 整数字段来稍微对模型进行非规范化。

然后您所要做的就是重写 save() 以使用 vote_difference() 方法计算分数。

这使得排序变得更加容易,并且可能减少您进行的数据库调用的数量。

You may want to consider denormalizing your model slightly by adding a vote_score integer field.

Then all you have to do is override save() to calculate the score using your vote_difference() method.

That makes sorting much easier, and likely reduces the number of database calls you are making.

清风无影 2024-09-10 08:45:21

reddit 算法基于计算重力的公式。 找到它

我从这个网站 Reddit算法

let t = (t1 – epoch)

(其中 t1 是发布帖子的时间)

let x be the number of up votes minus the number of down votes.

然后,

let y be:
  • 如果赞成票多于反对票,则为 1;
  • 如果反对票多于赞成票,则为 -1;
  • 如果数量相同,则为 0。

现在让

z = max({x,1})

我们有

ranking = C log10(z) + yt1

Where C is a constant (C = 45000).

The reddit algorithm is based on the formula for calculating gravity. I found it from this website

Reddit Algorithm

let t = (t1 – epoch)

(where t1 is the time the post was made)

let x be the number of up votes minus the number of down votes.

Then,

let y be:
  • 1 if there are more up votes than down votes,
  • -1 If there are more down voets than up votes,
  • 0 if there are the same number.

Now Let

z = max({x,1})

And We Have

ranking = C log10(z) + yt1

Where C is a constant (C = 45000).
无需解释 2024-09-10 08:45:21

我知道这不是对你问题的直接回答。但浏览一下 reddit 代码可能会非常有帮助。当我必须实现类似于 reddit 的半智能图像裁剪算法时,它对我很有帮助。

I know this is not a direct answer to your question. But taking a peek into reddit's code may be very helpful. It helped me when I had to implement a semi-inteligent image cropping algorithm similar to reddit's.

谁把谁当真 2024-09-10 08:45:21

我发布了一个名为 qhonuskan-votes 的投票应用程序,您可以从这里查看:https://github.com/ miratcan/qhonuskan-votes

I released a voting application called qhonuskan-votes, you can check it from here: https://github.com/miratcan/qhonuskan-votes

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文