How to annotate Django QuerySet with another object using subquery

Django 1.11 added Subqueries. 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 commenting out with " newest_commenter_email

" in this script, I would like the whole object newest_commenter

, for example:

from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')   
Post.objects.annotate(newest_commenter=Subquery(newest[:1]))

      

However, this results in the following error:

FieldError: Expression contains mixed types. You must set output_field

      

Is there a way to get around this?

+3


source to share


1 answer


In the subquery you missed values

, try this:

Post.objects.annotate(newest_commenter=Subquery(newest.values('author')[:1]))

      



where author is the commenter field in the comment model.

0


source







All Articles