0

可能かどうかはわかりませんが、正確なvote_type属性を持つモデルに関連付けられたすべての投票をカウントしたいと考えています。

モデルは次のとおりです。

class Link(models.Model):
    title       = models.CharField(max_length=200)
    . . . 

class Vote(models.Model):
    UP, DOWN = range(2)
    TYPE_CHOICES = [(UP, "Upvote"), (DOWN, "DownVote")]

    link = models.ForeignKey(Link, related_name='votes')
    vote_type = models.IntegerField(choices=TYPE_CHOICES, db_index=True)
    . . . 

これを使用してすべての票を数えました:

Link.objects.annotate(ups=Count('votes')).order_by('-ups')

そして、これを使用して私が望むものを達成できるかもしれないと考えました:

Link.objects.annotate(ups=Count('votes__vote_type__exact=1')).order_by('-ups')

しかし、ここでは filter() 構文を使用できないようです。

私はDjango 1.8.4を使用しています。

4

1 に答える 1

2

注釈を実行する前に、タイプに基づいて投票をフィルタリングできます。

Link.objects.filter(votes__vote_type=1).annotate(ups=Count('votes')).order_by('-ups')

ソース: https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-of-annotate-and-filter-clauses

于 2015-10-15T18:33:51.330 に答える