from django.db.models import Count from .models import Article, UserArticleState def with_user_state(articles, user): """Annotates an iterable of Article instances with is_read/is_starred/ is_saved_for_later booleans for the given user, in two queries total regardless of how many articles there are (no N+1). Accepts either a queryset or a plain list (search backends return plain lists already ordered by relevance), materializing it either way. """ articles = list(articles) if not articles: return articles states = { state.article_id: state for state in UserArticleState.objects.filter( user=user, article_id__in=[a.pk for a in articles] ) } for article in articles: state = states.get(article.pk) article.is_read = state.is_read if state else False article.is_starred = state.is_starred if state else False article.is_saved_for_later = state.is_saved_for_later if state else False return articles def unread_counts_by_feed(user): """{feed_id: unread_count} for every feed the user subscribes to, in one query — used by the sidebar, so it must stay cheap regardless of how many feeds/articles exist.""" rows = ( Article.objects.filter(feed__subscriptions__user=user) .exclude(user_states__user=user, user_states__is_read=True) .exclude(user_states__user=user, user_states__is_hidden=True) .values("feed_id") .annotate(unread=Count("id")) ) return {row["feed_id"]: row["unread"] for row in rows}