查询中外键的最大出现次数

Max occurrences of a foreign key inside query

我正在尝试在查询集(问题、选择)中获取外键(投票)出现次数最多的项。

I.E.我需要获得最受欢迎的投票才能在 JsonResponse 中设置 'winner' 属性。

任何关于我如何解决这个问题的帮助?

这是我的看法。

allchoices = [{
    'id':i.id,
    'question':i.question.id,
    'choice_text':i.choice_text,
    'votes':i.voter_set.all().count()
} for i in poll_choices]
return JsonResponse({
    "votes":choice.voter_set.all().count(),
    'winner':True,
    'success':True,
    'allchoices':allchoices
},safe=False,)

这些是我的模型:

class Voter(models.Model):
    # Authentication of anonymous users
    choice = models.ForeignKey('PollChoice', on_delete=models.CASCADE)
    question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE)
    

class PollChoice(models.Model):
    question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    
    def __str__(self):
        return self.choice_text
    

class PollQuestion(models.Model):
    question = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey('poll_creator',/\
         on_delete=models.CASCADE, null=False, blank=False)
    uuid = ShortUUIDField(length=8, max_length=12)
    
    def poll_choices(self):
        return self.pollchoice_set.all().annotate(voters=/\
            models.Count(models.F('voter'))).order_by('-voters')
    
    def choices(self):
        return self.pollchoice_set.all()

    def __str__(self):
        return f'{self.question}'

您可以按相关 Voter 的数量排序,其中:

from django.db.models import <strong>Count</strong>

poll_choice = PollChoice.objects.alias(
    <strong>num_voters=Count('voter')</strong>
)<strong>.latest('num_voters')</strong>

这将检索具有最多相关 VoterPollChoice。您可以进一步过滤 PollChoice,例如仅考虑 PollChoice 的某个 PollQuestion 具有:

from django.db.models import <strong>Count</strong>

poll_choice = PollChoice.objects.filter(question=<i>my_question</i>).alias(
    <strong>num_voters=Count('voter')</strong>
)<strong>.latest('num_voters')</strong>