我有三個模型:
class User:
screen_name = Charfield
class Post:
author = FK(User)
class Comment:
post = FK(Post, related_name=comment_set)
author = FK(User)
現在我想Post用以下方式注釋 s (原始注釋更復雜,添加更簡單的示例):
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))
在此之后,我想Post按欄位過濾 s 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 出了點問題,但不知道到底是什么。有什么想法嗎?
uj5u.com熱心網友回復:
你不能這樣做:prefetch_relateds不會出現在查詢中,這些是通過第二個查詢完成的。
您可以簡單地過濾:
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()
因此,如果您只想過濾,則無需預取。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/485276.html
