Pass or refer parent query value into subquery

94 views
Skip to first unread message

Sencer Hamarat

unread,
Jul 26, 2022, 11:27:23 AM7/26/22
to django...@googlegroups.com
Hi,

I need to pass the parent query book_id value into the subquery.
Here is the model and the current state of the query I reached.

class Publisher(models.Model):
    book = models.ForeignKey(Book)
    bundle = models.JSONField()


current_sales_count_query = Publisher.objects.filter(
            Q(book_id=F("book_id")) | Q(bundle__contains=F("book_id")),
        ).values('id')

query = Publisher.objects.filter(
             **query_params,
        ).select_related(
             'book',
        ).annotate(
            current_sales_count=Count(Subquery(current_sales_count_query)),
        )

Sql Output:

SELECT "publisher"."id",
       ......
       COUNT((SELECT U0."id"
              FROM "publisher" U0
              WHERE (U0."book_id" = (U0."logbook_id") OR U0."current_tree_level" @> (U0."book_id") "current_rejected_count",
       "books"."id",
       ........
FROM "publisher"
         INNER JOIN "books" ON ("publisher"."book_id" = "books"."id")
WHERE "publisher"."book_id" IN (1, 2, 12)
GROUP BY "publisher"."id", "books"."id"

But subquery insists on using book_id from itself with that query.
What should I do to make things right?



King regards,
Sencer HAMARAT

Ross Meredith

unread,
Jul 26, 2022, 11:34:54 AM7/26/22
to django...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACp8TZjKRQS2_OZsTey%2BPiJJF2nDzCjLR3uf09Y6seZ9_gc5Yg%40mail.gmail.com.

Sencer Hamarat

unread,
Jul 26, 2022, 12:01:52 PM7/26/22
to django...@googlegroups.com
Thanks Ross,
Very appreciated.
That's what I need.

I'm also having a problem with this query after I implemented the solution:

I believe, 
Q(bundle__contains=OuterRef("book_id"))
part of the query is expecting an array instead of direct value.

I'm getting this error:

ProgrammingError: operator does not exist: jsonb @> bigint
LINE 1: ...lisher"."book_id") OR U0."bundle" @> ("publisher_...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

Is there a way to handle this error? How can I cast the value into an array?



Regards,
Sencer HAMARAT



Ross Meredith

unread,
Jul 26, 2022, 2:58:11 PM7/26/22
to django...@googlegroups.com
Sorry I haven't used the JSONField myself before.

Reply all
Reply to author
Forward
0 new messages