﻿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
24770	Model instances are dropped by annotate when reverse foreign key is empty.	Ian Foote	nobody	"I ran across an odd interaction between `annotate`, `Sum`, `Case`, `When` and a reverse `ForeignKey`. I've prepared a [https://github.com/Ian-Foote/django-annotate-bug/blob/master/bug/tests/test_query.py#L10-L24 minimal testcase]. I expect the `Post` I created to be in the `queryset`, annotated with `0`, but instead the `queryset` is empty.

The query generated by the annotate looks like:
{{{
SELECT ""bug_post"".""id"", ""bug_post"".""created"", SUM(CASE WHEN ""bug_comment"".""created"" > (""bug_post"".""created"") THEN 1 ELSE 0 END) AS ""unread_comments"" FROM ""bug_post"" INNER JOIN ""bug_comment"" ON ( ""bug_post"".""id"" = ""bug_comment"".""post_id"" ) GROUP BY ""bug_post"".""id"", ""bug_post"".""created""
}}}

I initially ran into this on postgres, but my minimal testcase also shows it on sqlite."	Bug	new	Database layer (models, ORM)	1.8	Normal				Unreviewed	0	0	0	0	0	0
