[Fixed]-Django ORM join subtable in query

1👍

When you add tables with extra, they get added to the from list, which does not accept an sql statement.
I don’t think you need to use extra at all here, you can get a similar query with the ORM without the need to join on a select statement. The following code, using filtering and annotations, will give the same results as much as I was able to understand your query:

ApplicationUser.objects.filter(
    Q(itinerary__location_id = F('friends__home_location_id')) |
    Q(friends__home_location__isnull=True),
    id=28,                                                    
    ).values_list(
        'itinerary__id', 'friends__home_location_id'
    ).annotate(location_count = Count('friends__home_location_id')
    ).values_list('itinerary__id', 'location_count')
👤noamk

Leave a comment