I found what looks like the same Ticket ,But I'm not sure it's the same
reason [https://code.djangoproject.com/ticket/30655]
Here is a simple example that shows the contrary.
Models:
{{{
class Exam(models.Model):
paper = models.ForeignKey(ExamPaper, related_name='paper_exam',
on_delete=models.CASCADE, blank=True, null=True)
class StudentPaper(models.Model):
user = models.ForeignKey(User, related_name='user_exam_paper',
on_delete=models.CASCADE)
exam = models.ForeignKey(Exam, related_name='exam_student_paper',
on_delete=models.CASCADE)
}}}
Shell Output:
{{{
>>> from ExamManage.models import*
>>> exam = Exam.objects.first()
>>> exam.exam_student_paper.filter(is_pass=True).values('user_id').count()
521
>>> support_pass_userids =
exam.exam_student_paper.filter(is_pass=True).values('user_id').distinct()
>>> support_pass_userids.count()
484
>>> print(support_pass_userids.query)
SELECT DISTINCT `ExamManage_studentpaper`.`user_id`,
`ExamManage_studentpaper`.`id` FROM `ExamManage_studentpaper` WHERE
(`ExamManage_studentpaper`.`exam_id` = 5 AND
`ExamManage_studentpaper`.`is_pass`) ORDER BY
`ExamManage_studentpaper`.`id` DESC
>>> len(support_pass_userids)
521
>>> support_pass_userids.count()
521
>>> print(support_pass_userids.query)
SELECT DISTINCT `ExamManage_studentpaper`.`user_id`,
`ExamManage_studentpaper`.`id` FROM `ExamManage_studentpaper` WHERE
(`ExamManage_studentpaper`.`exam_id` = 5 AND
`ExamManage_studentpaper`.`is_pass`) ORDER BY
`ExamManage_studentpaper`.`id` DESC
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/33382>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* status: new => closed
* resolution: => duplicate
* component: Uncategorized => Database layer (models, ORM)
Comment:
Duplicate of #30655. Please see my
[https://code.djangoproject.com/ticket/30655#comment:2 comment]:
''"`count()` calls `SELECT COUNT(*)` (as described in
[https://docs.djangoproject.com/en/stable/ref/models/querysets/#count
docs]) **without taking ordering into account**,..."''
see also a
[https://docs.djangoproject.com/en/stable/ref/models/querysets/#distinct
note] about using `distinct()` on an ordered queryset.
--
Ticket URL: <https://code.djangoproject.com/ticket/33382#comment:1>
Comment (by crazy):
Thanks for your patience, now I understand why there difference, because
the `id` field is used for sorting, it interfered with the `distinct`
results. So if count records, should use `count`.
--
Ticket URL: <https://code.djangoproject.com/ticket/33382#comment:2>