问题描述
我正在学习 Django 并在我的网站上使用 sqlite3,直到今天,我将数据库更改为 Postgres。
我的网站有点模仿 Facebook。我有一个 ListView 将列出所有帖子。在 get_queryset()
中,我用一些附加信息对每个帖子进行注释,例如喜欢和不喜欢的数量、评论数量、当前登录用户是否关注了帖子的所有者。我还对结果进行了分页,以便我的网站每页仅显示 5 个帖子。
这是我的代码:
class PostListView(FormMixin,ListView):
model = Post
paginate_by = 5
template_name = "network/newsFeed.jinja"
body_title = "All Posts"
context_object_name = "posts"
form_class = PostCreateForm
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['form'] = self.get_form()
context['body_title'] = self.body_title
return context
def get_queryset(self):
queryset = Post.objects.select_related('owner').annotate(
comment_count=Count('comments',distinct=True),like_count=Count(
Case(
When(likes__is_like=True,then=Value(1)),output_field=IntegerField
),distinct=True
),dislike_count=Count(
Case(
When(likes__is_like=False,).order_by('-created_time') # improve: do we need query all?
if self.request.user.is_authenticated:
return queryset.annotate(
follow_already=Exists(
Follow.objects.filter(followed=OuterRef('owner'),follower=self.request.user)
),like_already=Exists(
Like.objects.filter(owner=self.request.user,post_parent=OuterRef('pk'),is_like=True)
),dislike_already=Exists(
Like.objects.filter(owner=self.request.user,is_like=False)
)
)
return queryset.annotate(
follow_already=Value(False,output_field=BooleanField()),like_already=Value(False,output_field=BooleanField())
)
我的网站对 sqlite3 没问题。但是在更改为 Postgres 时出现错误,该错误发生在 get_internal_type()
中的第 17 行(参见图片),其中说明:
TypeError: get_internal_type() missing 1 required positional argument: 'self'
The line raises the error 你能解释一下这里发生了什么吗?我想不明白? 我认为原因是注释的使用。当我删除它们时,它起作用了。还有一件事,最佳实践是什么:在哪里放置注释,我意识到我正在注释整个查询集,但只在其中使用 5 个对象。 感谢您的阅读^^
解决方法
目前还不清楚,但我找到了根本原因。我的代码在指示 output_field 的行中缺少括号,用于注释 like_count 和 dislike_count。他们应该是这样的:
output_field=IntegerField() # with parenthesis
谢谢^^