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 [email protected].
To post to this group, send email to [email protected].
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/f81e26c5-38fa-4675-86b3-45e782175335%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to