In Django version 1.11, Subquery expressions were added. I was hoping to use this feature to select a related model object based on some filters.
This is an example from the 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]))
I would like to do the same, but instead of just annotating with the "newest_commenter_email" in this scenario, I'd like the whole Comment object saved to a newest_comment annotation, like so:
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]))
However, this results in the following error:
FieldError: Expression contains mixed types. You must set output_field
Is there a way around this?
Comment.objects.filter(post=pk).order_by('-created_at').select_related('post')[:1]. Then you preoloaded thePostobject with the most recent comment. This way you get the whole Post and Comment model.