1👍
You can work with a subquery to determine this, so:
from django.db.models import OuterRef, Subquery
Company.objects.annotate(
last_is_friend=SubQuery(
Customer.objects.filter(
company=OuterRef('pk')
).order_by('-created_at').values('friend')[:1]
)
).filter(last_is_friend=True)
The subquery will thus make an ordered collection of Customer
s that are linked to the Company
, we pick the friend
value for the first Customer
of these customers. This is what the annotation is doing.
Finally we filter out the Company
s that do not have a friend
as last Customer
.
Source:stackexchange.com