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)

现在我想按以下方式注释Posts(原始注释较复杂,添加了较简单的示例):

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字段过滤Posts,但我收到以下错误:

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

因此,如果您只想过滤,则不需要预取。

相关内容

  • 没有找到相关文章

最新更新