Andru
Andru

Reputation: 260

How to get SQL query for query with Subquery?

I have a query

q = Product.objects \
    .annotate(t=Subquery(Purchase.objects.filter(user=user)))

and when I do print(q.query) I get the following exception:

{FieldError} Cannot resolve expression type, unknown output_field

What to do and why they can't resolve the expression type?

Upvotes: 0

Views: 575

Answers (1)

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7404

You need to use .values, to select the field you want to annotate from user

q = Product.objects.annotate(t=Subquery(Purchase.objects.filter(user=user).values('pk')))

Upvotes: 1

Related Questions