@@ -2165,46 +2165,16 @@ def with_children(self):
2165
2165
def with_occurrence_counts (self ) -> models .QuerySet :
2166
2166
"""
2167
2167
Count the number of occurrences for a taxon and all occurrences of the taxon's children.
2168
- """
2169
- qs = self .get_queryset ()
2170
2168
2171
- # Subquery to get all child taxa IDs
2172
- import json
2169
+ @TODO Try a recursive CTE in a raw SQL query,
2170
+ or count the occurrences in a separate query and attach them to the Taxon objects.
2171
+ """
2173
2172
2174
- child_taxa = qs .filter (
2175
- parents_json__contains = models .Value (
2176
- json .dumps ([{"id" : models .OuterRef ("pk" )}]), output_field = models .JSONField ()
2177
- )
2178
- ).values ("pk" )
2179
-
2180
- # Debugging: Log the SQL for child_taxa
2181
- logger .info (f"SQL for child_taxa: { child_taxa .query } " )
2182
-
2183
- # Debugging: Count and log the number of child taxa
2184
- child_count = child_taxa .count ()
2185
- logger .info (f"Number of child taxa found: { child_count } " )
2186
-
2187
- # Debugging: Log a sample of child taxa
2188
- sample_children = list (child_taxa [:5 ])
2189
- logger .info (f"Sample of child taxa: { sample_children } " )
2190
-
2191
- # Annotate with occurrence counts
2192
- qs = qs .annotate (
2193
- occurrences_count_bulk = models .Count (
2194
- "occurrences" ,
2195
- filter = models .Q (
2196
- models .Q (occurrences__determination_id = models .F ("pk" ))
2197
- | models .Q (occurrences__determination_id__in = models .Subquery (child_taxa ))
2198
- ),
2199
- distinct = True ,
2200
- )
2173
+ raise NotImplementedError (
2174
+ "Occurrence counts can not be calculated in a subquery with the current JSONField schema. "
2175
+ "Fetch them per taxon."
2201
2176
)
2202
2177
2203
- # Debugging: Log the final SQL query
2204
- logger .info (f"Final SQL query: { qs .query } " )
2205
-
2206
- return qs
2207
-
2208
2178
2209
2179
class TaxonParent (pydantic .BaseModel ):
2210
2180
"""
0 commit comments