4

I have two Django models, X and Y, I have a query set of X objects and I want to join it against a queryset of Y objects.

I can't use raw SQL here as the API of the code I'm working with expects a queryset to be returned.

I can do the following

def my_method(x_queryset):
    y_subquery = Y.objects.distinct('x_id').order_by('-dt')
    return x.queryset.filter(id__in==y_subquery)

This generates the approximate SQL:

SELECT * 
FROM x 
WHERE id IN (SELECT DISTINCT ON (x_id) x_id 
             FROM y 
             ORDER BY dt DESC)

But the above is not exactly what I want (and not equivalent to what I need). What I really want to to is a LEFT OUTER JOIN, with the rough SQL being:

SELECT x.* 
FROM x 
LEFT OUTER JOIN 
    (SELECT DISTINCT ON (x_id) x_id, created 
     FROM y 
     ORDER BY dt DESC) sub ON x.id = sub.x_id;

I cannot figure out how to do a custom left outer join against a subquery with Django ORM, pseudo code of what I would like is:

def my_method(x_queryset):
    y_subquery = Y.objects.distinct('x_id').order_by('-dt')
    return x.queryset.left_outer_join(y_subquery, {'id': 'x_id'})

Any help would be greatly appreciated!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
J. Doe
  • 555
  • 1
  • 6
  • 15
  • I don't think it is currently possible. For some cases, [FilteredRelations](https://docs.djangoproject.com/en/4.0/ref/models/querysets/#filteredrelation-objects) could help. – mfit Jun 08 '22 at 09:15

0 Answers0