﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
36197	Model.relatedmanager.count() always 0 for custom ManyToMany relationships with through model with to_fields	mfontana-elem	Simon Charette	"While upgrading my codebase to Django 5.1 I started noticing some tests were failing. At the end of the day, the reason was that, given an object's manager for a `ManyToMany` relation I was getting `object.relatedmanager.count() != len(object.relatedmanager.all())`. The LHS was always zero.

To illustrate my setup, I have the following models:
{{{
from django.db import models


class Course(models.Model):
    uuid = models.UUIDField(unique=True, editable=False, verbose_name=""UUID"")
    title = models.CharField(max_length=200)

class Student(models.Model):
    uuid = models.UUIDField(unique=True, editable=False, verbose_name=""UUID"")
    name = models.CharField(max_length=100)
    courses = models.ManyToManyField(Course, through=""CourseStudent"", related_name='students')

class CourseStudent(models.Model):
    course = models.ForeignKey(Course, to_field=""uuid"", on_delete=models.RESTRICT, null=False)
    student = models.ForeignKey(Student, to_field=""uuid"", on_delete=models.RESTRICT, null=False)
}}}

And the problem is that it `course.students.count()` generates the following SQL (both for SQLite and Postgres):
`SELECT COUNT(*) AS ""__count"" FROM ""courses_coursestudent"" WHERE ""courses_coursestudent"".""course_id"" = '00000000000000000000000000000001'`, 
which is of course wrong.

Under the exact same setup, Django 5.0 generates:
`SELECT COUNT(*) AS ""__count"" FROM ""courses_student"" INNER JOIN ""courses_coursestudent"" ON (""courses_student"".""uuid"" = ""courses_coursestudent"".""student_id"") WHERE ""courses_coursestudent"".""course_id"" = '0817704cdf2d478dba5d629b8997f73b'`.

I attach a `.zip` containing a `Dockerfile` and a `src` directory to easily reproduce this behavior.

Best regards,"	Bug	closed	Database layer (models, ORM)	5.1	Release blocker	fixed		ontowhee Simon Charette Mariusz Felisiak	Ready for checkin	1	0	0	0	0	0
