【发布时间】:2017-11-30 16:51:42
【问题描述】:
在 Django 1.11 版中,添加了Subquery expressions。我希望使用此功能根据一些过滤器选择相关的模型对象。
这是来自documentation的示例:
from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))
我也想做同样的事情,但在这种情况下,我希望将整个 Comment 对象保存到 newest_comment 注释中,而不是仅使用“newest_commenter_email”进行注释,如下所示:
from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_comment=Subquery(newest[:1]))
但是,这会导致以下错误:
FieldError: Expression contains mixed types. You must set output_field
有没有办法解决这个问题?
【问题讨论】:
-
也许你可以从评论模型开始?
Comment.objects.filter(post=pk).order_by('-created_at').select_related('post')[:1]。然后,您使用最新评论预加载了Post对象。这样你就可以得到整个 Post and Comment 模型。