Hello Jose, I wouldn't be surprised if this was caused by a Django bug with prefetches doing weird things when the same model is referenced through different relations[0].
Simon [0] https://code.djangoproject.com/ticket/26318 Le samedi 4 mars 2017 13:36:20 UTC-5, Jose Kilo a écrit : > > Hi all, > > I'm trying to use an annotated queryset inside a Prefetch object. For some > reason I'm not getting the expected result. > This is a simplified version of my models and query. > > > class User(models.Model): > > following = models.ManyToManyField('User', related_name='followers', > through='Follow') > > > class Follow(models.Model): > > following = models.ForeignKey(User, on_delete=models.CASCADE, > related_name='_followed') > followed = models.ForeignKey(User, on_delete=models.CASCADE, > related_name='_following') > > > def test(): > > User.objects.all().delete() > > user_1 = User.objects.create() > user_2 = User.objects.create() > > Follow.objects.create(following=user_1, followed=user_2) > > queryset = ( > User.objects.all() > .prefetch_related( > Prefetch( > 'followers', to_attr='prefetched_annotated_followers', > queryset=(User.objects.all().annotate( > followers_count=Count('followers', distinct=True), > )) > ), > Prefetch( > 'followers', to_attr='prefetched_followers', > queryset=User.objects.all() > ), > ) > ) > > user = queryset.last() > print(list(user.followers.all())) # [<User: User object>] > print(user.prefetched_followers) # [<User: User object>] > print(user.prefetched_annotated_followers) # [] > > return queryset > > > Why the last result is empty ? > > Just in case, I added 'prefetched_followers' to compare both results. If > I remove it, 'prefetched_annotated_followers' still doesn't get anything. > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a79f26af-b4ef-4ba7-9c5a-353a900d891a%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.