发布于2020-10-30 21:53 阅读(880) 评论(0) 点赞(13) 收藏(2)
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.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
And to traverse a relationship in a query in Django, you use the double underscore syntax, not dots. So:
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
Copyright © 2018-2019 python黑洞网 All Rights Reserved 版权所有，并保留所有权利。 京ICP备18063182号-1