Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6011233
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T02:13:50+00:00 2026-05-23T02:13:50+00:00

I’ve got two models: class Post(models.Model): #some fields pass class Vote(models.Model): post = mdoels.ForeignKey(Post)

  • 0

I’ve got two models:

class Post(models.Model):
    #some fields
    pass

class Vote(models.Model):
    post = mdoels.ForeignKey(Post)
    value = models.IntegerField()

Votes’ value can be either 1 or -1 (user can vote up or down).

How can i get a list of posts, ordered by their rating?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T02:13:51+00:00Added an answer on May 23, 2026 at 2:13 am

    You have to use annotation. https://docs.djangoproject.com/en/dev/topics/db/aggregation/

    class Post(models.Model):         
        name = models.CharField(max_length=20)
    
    class Vote(models.Model):
        post = models.ForeignKey(Post)
        value = models.IntegerField()
        type = models.CharField(max_length=2, choices=(("AW", "Awesomeness"), ("US", "Usefulness")))
    

    Then you need to import Sum and can get a list of posts ordered by their vote_total like:

    from django.db.models import Sum
    Post.objects.annotate(vote_total=Sum('vote__value')).order_by('-vote_total')
    

    EDIT:
    Here’s an example. Create several post objects and Vote Objects

    Post.objects.get_or_create(id=1, name="post1")
    Post.objects.get_or_create(id=2, name="post2")
    Post.objects.get_or_create(id=3, name="post3")
    Post.objects.get_or_create(id=4, name="post4")
    Vote.objects.get_or_create(id=1, post_id=2, value=1, type="AW")
    Vote.objects.get_or_create(id=2, post_id=2, value=1, type="AW")
    Vote.objects.get_or_create(id=3, post_id=2, value=1, type="US")
    Vote.objects.get_or_create(id=4, post_id=2, value=1, type="US")
    Vote.objects.get_or_create(id=5, post_id=3, value=-1, type="AW")
    Vote.objects.get_or_create(id=6, post_id=3, value=-1, type="AW")
    Vote.objects.get_or_create(id=7, post_id=4, value=-1, type="AW")
    

    Then posts = Post.objects.annotate(vote_total=Sum('vote__value')).order_by('-vote_total') will lead to [(post.name, post.vote_total) for post in posts] being.

    [(u'post2', 4), (u'post4', -1), (u'post3', -2), (u'post1', None)]
    

    This has an issue as things with no posts go at the very end. As django’s Sum aggregation function takes the sum of no entries as None, not 0. This could be solved if you initially gave every post a vote with value 0 (or value 1 like reddit’s system), you wouldn’t get the None: e.g.:

    for p in Post.objects.all():
        Vote.objects.get_or_create(post_id=p.id, value=0)
    

    Then you’ll get

    >>> [(p.name, p.vote_total) for p in
         Post.objects.annotate(vote_total=Sum('vote__value')).order_by('-vote_total')]
    [(u'post2', 4), (u'post1', 0), (u'post4', -1), (u'post3', -2)]
    

    EDIT: Added type to the Vote model (done above), per comment about different vote types.
    You should be able to do something like (replace ‘yourappname’ with the name of your application to get the right db table):

    select_dict = dict(vote_total = "SELECT SUM(value) FROM yourappname_vote WHERE yourappname_vote.post_id = yourappname_post.id",
                       awesome_total = "SELECT SUM(value) FROM yourappname_vote WHERE yourappname_vote.post_id = yourappname_post.id AND yourappname_vote.type = 'AW' ",
                       useful_total = "SELECT SUM(value) FROM yourappname_vote WHERE yourappname_vote.post_id = yourappname_post.id AND yourappname_vote.type = 'US' ",)
    
    posts = Post.objects.all().extra(select = select_dict).order_by('-vote_total')
    
    >>> [(p.name, p.vote_total, p.awesome_total, p.useful_total) for p in posts]
    [(u'post2', 4, 2, 2),
     (u'post1', 0, 0, 0),
     (u'post4', -1, -1, 0),
     (u'post3', -2, -2, 0)]
    

    Now each post now will have a vote_total, as well awesome_total and useful_total in one query to the database. A bit uglier than the ORM, but still quite readable (and this is how the Sum aggregation works. ). You still will have to give each category of votes an initial vote to get past the None appearing out of order.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have some data like this: 1 2 3 4 5 9 2 6
i got an object with contents of html markup in it, for example: string
I'm trying to create an if statement in PHP that prevents a single post
I want to count how many characters a certain string has in PHP, but
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.