2

This is the models.py

class CompetitionEntry(models.Model):
    submitter = models.ForeignKey(User)
    pic = models.ImageField(upload_to=images, blank=True, null=True)

class CompetitionEntryVote(models.Model):
    voted_entry = models.ForeignKey(CompetitionEntry)

class Entrylikes(models.Model):
    ip_address    = models.IPAddressField()
    liked_entry   = models.ForeignKey(CompetitionEntry)

This is the views.py (i think problem is here)

def show_all_entries(request, id):
    entries = CompetitionEntry.objects.filter(competition__id__exact=comp.id).annotate(vote_count=Count('competitionentryvote'), likes_count=Count('entrylikes'))

    return render(request, "show_all.html", {
        "entries": entries,
        })

show_all.html

{% for item in entries %}

Votes = {{item.vote_count}}   Likes= {{item.likes_count}}

{% endfor %}
  1. The problem here is that Both the votes and likes are same in the output. i,e votes=likes = likes

  2. and if i rewrite views to show only one of either votes or likes , the page works perfectly.

  3. and in views.py if i used entries = CompetitionEntry.objects.filter(competition__id__exact=comp.id).annotate(vote_count=Count('competitionentryvote')).annotate(likes_count=Count('entrylikes')) I get the same result as 1 above

1
  • I have removed contents from the models.py and views.py above, because they are too large to paste here. Hope this does not takes away the main point out of the question . Commented May 27, 2013 at 18:37

1 Answer 1

7

The Count aggregate works by mapping to a SQL COUNT() expression. See the documentation here.

Since the query you provide will yield only one set of rows for the entire query, the value for COUNT() may be the same in your case. You could try to set distinct=True as suggested in the documentation:

If distinct=True, the count will only include unique instances. This is the SQL equivalent of COUNT(DISTINCT ). The default value is False.

I.e.

CompetitionEntry.objects.filter(...).annotate(vote_count=Count('competitionentryvote', distinct=True))
   .annotate(likes_count=Count('entrylikes', distinct=True))
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry i didn't get the point here(i only have basic knowledge of SQL). So is it not possible include both the counts here ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.