Tuesday, July 26, 2022

Pass or refer parent query value into subquery

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

--
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+unsubscribe@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.

No comments:

Post a Comment