簡體   English   中英

Django如何在prefetch_related中注釋

[英]Django how to annotate in 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))

在此之后,我想通過comment_set__comment_author_screen_name_seen_by_user字段過濾Post ,但我收到以下錯誤:

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()

因此,如果您只想過濾,則無需預取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM