﻿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
25028	annotation with Q object duplicates results	karyon	nobody	"consider the following models:


{{{
class UserProfile(models.Model):
    pass

class Group(models.Model):
    name = models.CharField(max_length=255)
    users = models.ManyToManyField(UserProfile, related_name='groups')
}}}

and the following test:
{{{
def test_annotation(self):
    group1 = Group.objects.create(name=""group1"")
    group2 = Group.objects.create(name=""group2"")
    user = UserProfile.objects.create()
    user.groups = [group1, group2]
    users = UserProfile.objects.all().annotate(is_group1=ExpressionWrapper(Q(groups__name=""group1""), output_field=BooleanField()))
    for u in users:
        print(u.is_group1)
    print(users.query)
    self.assertEqual(users.count(), 1)
}}}

this prints the following:

{{{
Creating test database for alias 'default'...
1
0
SELECT ""testapp_userprofile"".""id"", ""testapp_group"".""name"" = group1 AS ""is_group1"" FROM ""testapp_userprofile"" LEFT OUTER JOIN ""testapp_group_users"" ON ( ""testapp_userprofile"".""id"" = ""testapp_group_users"".""userprofile_id"") LEFT OUTER JOIN ""testapp_group"" ON ( ""testapp_group_users"".""group_id"" = ""testapp_group"".""id"" )
F
<snip>
AssertionError: 2 != 1
}}}


the annotation is supposed to add a bool to the user indicating whether that user is part of some group or not. i haven't found an easier way to do it. this worked for us until we had a user that was in two groups at the same time.

for some reason the annotation with the Q object causes the user the appear two times in the result, once with is_group1==True, once with is_group1==False. if i make the user have only one group, the test succeeds."	Bug	closed	Uncategorized	1.8	Normal	duplicate		karyon	Unreviewed	0	0	0	0	0	0
