+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

How to implement upvote/downvote via over-riding a model manager in Django/Python

发布于2020-10-30 21:53     阅读(880)     评论(0)     点赞(13)     收藏(2)


0

1

2

3

4

5

6

I'm using Python 2.7, Django 1.5. In models.py, I have:

class Link(models.Model):
    submitter = models.ForeignKey(User)
    url = models.URLField("URL", max_length=250, blank=True)
    with_votes = LinkVoteCountManager()

    def __unicode__(self):
        return self.url

class LinkVoteCountManager(models.Manager):
    def get_query_set(self): 
        return super(LinkVoteCountManager, self).get_query_set().annotate(votes=Count('vote')).order_by('-votes')

class Vote(models.Model):
    voter = models.ForeignKey(User) 
    link = models.ForeignKey(Link) 

Next, in views.py I have:

class LinkListView(ListView):
    model = Link
    queryset = Link.with_votes.all()

The above correctly gives me a count of votes aggregated per link. Now, taking it to the next level, I want to incorporate downvotes into this set up as well. I included a value = models.IntegerField(default=0) attribute in Vote class (to capture -1 and 1 values), and changed votes=Count('vote') to votes=Count('vote.value') in my Custom Manager.

Unfortunately, it seems that is not how Custom Managers work. I'm now stumped as to how to implement upvote/downvote in this setup, in an efficient, elegant way. Being a Django newbie doesn't help of course.

Any gurus who can shed light on how they would traverse this problem are more than welcome!


解决方案


No, that is not how aggregation works: your problem is there, and has nothing at all to do with managers.

For a start, to correctly calculate a sum of positive and negative votes, you need Sum, not Count.

And to traverse a relationship in a query in Django, you use the double underscore syntax, not dots. So:

...annotate(votes=Sum('vote__value')).

0

1

2

3

4

5

6

7

8

9



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/609633/77aff3a021c3bf333411/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

13 0
收藏该文
已收藏

评论内容:(最多支持255个字符)