#25028: annotation with Q object duplicates results
-------------------------------+--------------------
     Reporter:  karyon         |      Owner:  nobody
         Type:  Bug            |     Status:  new
    Component:  Uncategorized  |    Version:  1.8
     Severity:  Normal         |   Keywords:
 Triage Stage:  Unreviewed     |  Has patch:  0
Easy pickings:  0              |      UI/UX:  0
-------------------------------+--------------------
 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.

--
Ticket URL: <https://code.djangoproject.com/ticket/25028>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/049.b1cf6e3670fe033a257798ee5ef54f9f%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to