﻿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
27123	prefetch_related return mistaken result	mostafa	nobody	"I have model like this :

{{{
class GlobalTeam(models.Model):
    team_name = models.CharField(max_length=100)
    user_profiles = models.ManyToManyField(UserProfile, related_name='user_teams')
    team_admin = models.ForeignKey(UserProfile, related_name='head_teams')
}}}

and this

{{{

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
}}}


now, I have a queryset like this:

{{{
my_teams =  GlobalTeam.objects.filter(Q(team_admin__user=user) | Q(user_profiles__user=user)).select_related(
    'team_admin',
    'team_admin__user'
).prefetch_related(
    'user_profiles',
    'user_profiles__user',
).annotate(
    user_cnt=(
        Count('user_profiles', distinct=True) +
        1
    ),
).distinct()

}}}


I don't know what but I get this outputs:

{{{
>>> my_teams[0].user_profiles.all()
[<UserProfile: a>, <UserProfile: b>, <UserProfile: c>]
>>> my_teams[1].user_profiles.all()
[<UserProfile: d>]
>>> for team in my_teams:
...  print(team.user_profiles.all())
... 
[<UserProfile: a>, <UserProfile: b>, <UserProfile: c>, <UserProfile: d>]
[]
>>> my_teams[0].user_profiles.all()
[<UserProfile: a>, <UserProfile: b>, <UserProfile: c>, <UserProfile: d>]

}}}


my psql version is: psql (PostgreSQL) 9.3.13
my django version is: 1.9.9


"	Bug	closed	Database layer (models, ORM)	1.9	Normal	needsinfo	prefetch_related, ORM, postgresql	mail@…	Accepted	0	0	0	0	0	0
