[Answered ]-Django remove duplicates in queryset and access their list of foreign key

2๐Ÿ‘

โœ…

I think a custom Prefetch object will do the trick

followings = user.socialprofile.follows.all()

items = Item.objects.filter(
            storage__user__in=followings.values('user')
        ).distinct().prefetch_related(
            models.Prefetch('storage_set',
                queryset=Storage.objects.filter(
                   user__in=followings.values('user')
                ),
                to_attr='storage_from_followings'
            )
        )

#in the template
{% for item in items %}
    {{ item.title }}
    {% for x in item.storage_from_followings %}
        {{ x.review }} {{ x.rating }}
    {% endfor %}
{% endfor %}
๐Ÿ‘คTodor

Leave a comment