Hi,
Perhaps this could help you:
I had to find how many versions of each "edge" object without using a db version column
So basically for this kind of dataset:
'''
| ID | edge_id | geom |
+====+=========+=======+
| 1 | 22 | yyyyy |
| 2 | 22 | xxxxx |
| 3 | 11 | aaaaa |
'''
I expected a queryset like
'''
[{'id':1, 'edge_id':22, 'geom':'yyyyy', 'counter': 2}, {'id':2, 'edge_id':22, 'geom':'xxxxx', 'counter': 2}, {'id':3, 'edge_id':11, 'geom':'aaaaaa', 'counter': 1}]
'''
So I used this kind of django request:
'''
from django.db.models import Count, IntegerField, OuterRef, Subquery
counted_edges = Edge.objects.values('edge_id').filter(
edge_id=OuterRef('edge_id'),
).annotate(
counter=Count('edge_id')
).order_by()
annotated_edges = Edge.objects.all().annotate(
pg_counter=(Subquery(
counted_edges.values('counter'), output_field=IntegerField()
)),
)
'''
So if I needed only the instances where my 'counter' is greater then 1 I think it will be done like this:
'''
# .......
annotated_edges.filter(pg_counter__gt=1)
'''
I don't know if there is any better solution with raw SQL but hope this can help