python - How to add two sql columns together with django? -


i have 2 database tables, story , storyvote want extract information story highest amount of votes. should in theory easy guess way have constructed database table may have made more complicated (its still possible change structure though).

the 2 database tables designed following way:

class story(models.model):     user = models.foreignkey(user)     date_added = models.datetimefield(auto_now_add=true)     date_modified = models.datetimefield(auto_now=true)     location = models.charfield(max_length=100)     title = models.charfield(max_length=150)     description = models.charfield(blank=true, null=true, max_length=2000)     story_text = models.textfield()      def __unicode__(self):         return self.title  class storyvote(models.model):     votes = models.integerfield()     story_vote_type = models.charfield(max_length=100)     story = models.foreignkey(story, related_name="votes")      def __unicode__(self):         return self.votes 

as can see model above have column named "story_vote_type" either "up" or "down". example wont work:

for story in s:     print story.title + " has " + str(story.votes.all().count()) + " votes." 

if filter out have specify either "story_vote_type=up" or "story_vote_type=down" , im not sure how should storing results , adding them together.

how add upvotes , downvotes specific story here ?

so far have code adds numbers together:

for story in s: ...     votes = story.votes.all() ...     title = story.title ...     specific_votes = 0 ...     vote in votes: ...             if (title == story.title , vote.story_vote_type == "up"): ...                     specific_votes = vote.votes + specific_votes ...             else: ...                     specific_votes = vote.votes + specific_votes ...     print story.title + " has " + str(specific_votes) + " votes." 

all appriciated.

going problem description want to:

  1. get storytype max number of votes.
  2. get details of corresponding story.

this 1:

from django.db.models import max, f res = storyvote.objects.annotate(max_votes=max('votes')).filter(current_price=f('max_votes')) 

this how improve 1 2:

res = storyvote.objects.select_related('storyvote__story').annotate(max_votes=max('votes')).filter(current_price=f('max_votes')) 

as adding upvotes , downvotes specific story, think better approach have both upvote_count , downvote_count story in storytype. thought, since not aware of design of code.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -