https://docs.djangoproject.com/en/4.0/ref/models/expressions/#django.db.models.OuterRef

On Tue, Jul 26, 2022 at 4:27 PM Sencer Hamarat <[email protected]>
wrote:

> 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 [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CACp8TZjKRQS2_OZsTey%2BPiJJF2nDzCjLR3uf09Y6seZ9_gc5Yg%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CACp8TZjKRQS2_OZsTey%2BPiJJF2nDzCjLR3uf09Y6seZ9_gc5Yg%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAA1Tdz1N422oNtAkTtQpw1yu529PfdCPeevW%2BWbuBWfk_XO0RQ%40mail.gmail.com.

Reply via email to