[Answered ]-Django ORM queryset

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 Customers 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 Companys that do not have a friend as last Customer.

Leave a comment