Annotate and Subquery with 2 tables in 2 different databases

48 views
Skip to first unread message

Mạnh ĐỖ

unread,
Apr 20, 2023, 9:58:20 AM4/20/23
to Django users
I want to use annotate and subquery to join tables.
Table1 in database1 and table2 in database2. But it's not work.
I got the error:

 QuerySet.annotate() received non-expression(s): database1.


the code here:
from
django.db.models import Subquery, OuterRef, Count from app1.models import Table1 from app2.models import Table2 subquery = Table2.objects.filter(table1_id=OuterRef('id')).values('table1_id').annotate(count=Count('id')).values('count') queryset = Table1.objects.annotate(table2_count=Subquery(subquery, output_field=models.IntegerField()), using='database1')

Could anyone help me?

Jason

unread,
Apr 20, 2023, 3:44:13 PM4/20/23
to Django users
this won't work, you're doing things across two entire dbs.  So you'l have to implement all the logic in python to execute.
Reply all
Reply to author
Forward
0 new messages