python - Django querysets and foreign keys -


i've got reddit-like application. there "posts" , people vote on them or down. in template list posts , want able indicate whether person has voted on post or not.

it's little confusing because i'm passing queryset full of posts template iterate through each post display want know if there existing vote or not.

here code:

class submission(models.model):     submitter = models.foreignkey(user)     title = models.charfield("title", max_length=200)  class vote(models.model):     voter = models.foreignkey(user)     submission = models.foreignkey(submission)     vote_value = models.floatfield()  class submissionlistview(listview):     model = submission     queryset = submission.objects.extra(select={'total': 'ifnull((select sum(vote_value) ' + \         'from submissions_vote ' + 'where submissions_vote.submission_id = ' + 'submissions_submission.id), ' + \         '0)'}).order_by('-total')     paginate_by = 5 

ok can see i'm doing queryset extra() because want sum votes each post , display total on page. think efficient way this.

but if user viewing page has made vote particular submission need convey information template somehow. know can loop through each vote object in template , figure out there seems inefficient. i've been reading chaining querysets.. need here?

you add extra select:

queryset = submission.objects.extra(     select={'total': 'ifnull((select sum(vote_value) ' + \         'from submissions_vote ' + 'where submissions_vote.submission_id = ' + \         'submissions_submission.id), ' + '0)',     'has_voted': 'case when %d in (select voter_id submissions_vote ' + \         'submissions_vote.submission_id = submissions_submission.id) 1 else 0 end'     }, select_params=(self.request.user.pk,)).order_by('-total') 

i know isn't prettiest solution. try not write custom sql often, can't think of better. love know end doing.

edit: since need access self.request, need override get_queryset method:

def get_queryset(self):     return submission.objects.extra(     select={'total': 'ifnull((select sum(vote_value) ' + \         'from submissions_vote ' + 'where submissions_vote.submission_id = ' + \         'submissions_submission.id), ' + '0)',     'has_voted': 'case when %d in (select voter_id submissions_vote ' + \         'submissions_vote.submission_id = submissions_submission.id) 1 else 0 end'     }, select_params=(self.request.user.pk,)).order_by('-total') 

do instead of queryset variable


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -