I have this queryset below.
queryset = Contract.objects.select_related(
"company",
"user",
"user__profile",
"user__profile__address",
"user__profile__address__living_country",
"compensation__currency",
"job",
"benefit",
"payment_details",
"working_country",
"work_permit",
).prefetch_related(
Prefetch(
"partner_fee__partner__partner_countries",
queryset=CountryPartner.objects.annotate(contract_id=OuterRef("id")).all()
)
)
I have to annotate that contract_id
to filter that CountryPartner
. But it is not possible to use OuterRef
there. It always needs Subquery
of django.models
.
Ideally, I want to do this sql query in Django ORM:
select cc.id, cc.email, cc.residency_type, dc.country_id from core_contract cc
inner join public.core_partnerfee cp on cc.id = cp.contract_id
inner join public.core_partnerprofile c on cp.partner_id = c.id
inner join public.dicts_countrypartner dc on c.id = dc.partner_profile_id
where dc.country_id=cc.working_country_id
and dc.residency_type=cc.residency_type
and dc.partner_profile_id=c.id order by cc.id;
If I use Subquery inside CountryPartner filter it is going to take CountryPartnerId, not Contract ID. See below pls.
Prefetch(
"partner_fee__partner__partner_countries",
queryset=CountryPartner.objects.annotate(contract_id=SubQuery(Contract.objects.filter(id=OuterRef("id"))))
)
So, how to be? Django ORM is not able to do this?
New contributor
Nurymzhan Ayapbergen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.