Django как аннотировать в prefetch_related

У меня есть три модели:

class User:
    screen_name = Charfield


class Post:
    author = FK(User)


class Comment:
    post = FK(Post, related_name=comment_set)
    author = FK(User)

Теперь я хочу аннотировать Post следующим образом (оригинальная аннотация сложнее, добавлен более простой пример):

if is_student:
        comment_qs = Comment.objects.annotate(
            comment_author_screen_name_seen_by_user=Case(
                When(Q(is_anonymous=True) & ~Q(author__id=user.id), then=Value("")),
                default=F("author__screen_name"), output_field=CharField()
            ),
            comment_author_email_seen_by_user=Case(
                When(Q(is_anonymous=True) & ~Q(author__id=user.id), then=Value("")),
                default=F("author__email"), output_field=CharField()
            ),
        )
        queryset = queryset.annotate(
            post_author_screen_name_seen_by_user=Case(
                When(Q(is_anonymous=True) & ~Q(author__id=user.id), then=Value("")),
                default=F("author__screen_name"), output_field=CharField()
            ),
            post_author_email_seen_by_user=Case(
                When(Q(is_anonymous=True) & ~Q(author__id=user.id), then=Value("")),
                default=F("author__email"), output_field=CharField()
            ),
        )
    else:
        comment_qs = Comment.objects.annotate(
            comment_author_screen_name_seen_by_user=F("author__screen_name"),
            comment_author_email_seen_by_user=F("author__email")
        )
        queryset = queryset.annotate(
            post_author_screen_name_seen_by_user=F("author__screen_name"),
            post_author_email_seen_by_user=F("author__email"),
        )
queryset = queryset.prefetch_related(Prefetch("comment_set", queryset=comment_qs))

После этого я хочу отфильтровать Posts по полю comment_set__comment_author_screen_name_seen_by_user, но получаю следующую ошибку:

django.core.exceptions.FieldError: Unsupported lookup 'comment_author_screen_name_seen_by_user' for AutoField or join on the field not permitted

Но к этому полю можно получить доступ:

queryset[0].comment_set.all()[0].comment_author_screen_name_seen_by_user == "Foo Bar"

Я чувствую, что что-то не так с Prefetch, но не могу определить, что именно. Есть мысли?

Вы не можете этого сделать: prefetch_related в запросе не появляются, они выполняются через второй запрос.

Вы можете просто фильтровать с помощью:

Post.objects.filter(
    comment_set__author__screen_name='Foo Bar'
).distinct()

или вы можете фильтровать с помощью логики:

Post.objects.alias(
    comment_author_screen_name_seen_by_user=Case(
        When(Q(comment_set__is_anonymous=True) & ~Q(comment_set__author__id=user.id), then=Value('')),
                default=F('comment_set__author__screen_name'),
        output_field=CharField()
    )
).filter(
    comment_author_screen_name_seen_by_user='Foo Bar'
).distinct()

Таким образом, нет необходимости в предварительной выборке, если вы хотите только фильтровать.

Вернуться на верх