[Answered ]-Django: Determining if a user has voted or not

2๐Ÿ‘

โœ…

Iโ€™ve dealt with this before and solved it with extra more or less like so:

# annotate whether you've already voted on this item
table = Vote._meta.db_table
select = 'SELECT COUNT(id) FROM %s' %table
where1 = 'WHERE ' + table + '.user_id = %s'
where2 = 'AND ' + table + '.item_id = appname_item.id'
items = items.extra(
        select={'votes':" ".join((select, where1, where2,))},
        select_params=(request.user.id,)
    )

Effectively this takes a QuerySet of items and annotates each one with either a 0 or some number of votes. In my system I use unique_together = ('link', 'user') on Vote to make sure each user can only vote once, so the annotated data is either 0 or 1 (effectively boolean). It works quite well and avoids the n+1 problem.

๐Ÿ‘คGabriel Hurley

Leave a comment