11from __future__ import annotations
22
3+ from typing import TYPE_CHECKING
4+
35from django .db .models import (
46 BooleanField ,
57 Case ,
68 Exists ,
79 F ,
8- IntegerField ,
910 OuterRef ,
1011 Value ,
1112 When ,
1213)
13- from django .http import Http404 , HttpRequest
1414from django .shortcuts import get_object_or_404
1515from ninja import Query , Schema
1616from ninja .pagination import RouterPaginated
1717
1818from bats_ai .core .models import GRTSCells , Recording , Species , SpeciesRange
1919
20+ if TYPE_CHECKING :
21+ from django .http import HttpRequest
22+
2023router = RouterPaginated ()
2124
2225# Continental US sample frame ID, defaulting to CONUS GRTS when not specified.
2326CONUS_SAMPLE_FRAME_ID = 14
2427
25- _SPECIES_SCHEMA_FIELDS = (
26- "species_code" ,
27- "family" ,
28- "genus" ,
29- "species" ,
30- "common_name" ,
31- "species_code_6" ,
32- "category" ,
33- "pk" ,
34- )
35-
3628
3729class SpeciesSchema (Schema ):
3830 species_code : str | None
@@ -46,32 +38,6 @@ class SpeciesSchema(Schema):
4638 in_range : bool | None = None
4739
4840
49- def _primary_grts_cell (grts_cell_id : int ) -> GRTSCells :
50- order = GRTSCells .sort_order ()
51- whens = [When (sample_frame_id = sid , then = Value (rank )) for rank , sid in enumerate (order )]
52- cell = (
53- GRTSCells .objects .filter (grts_cell_id = grts_cell_id )
54- .exclude (geom_4326__isnull = True )
55- .annotate (
56- frame_rank = Case (
57- * whens ,
58- default = Value (len (order )),
59- output_field = IntegerField (),
60- ),
61- )
62- .order_by ("frame_rank" )
63- .first ()
64- )
65- if cell is None :
66- raise Http404 (f"No GRTS cell geometry found for grts_cell_id={ grts_cell_id } " )
67- return cell
68-
69-
70- def _species_values_qs (qs ):
71- """Restrict columns to SpeciesSchema (excluding optional in_range)."""
72- return qs .annotate (pk = F ("id" )).values (* _SPECIES_SCHEMA_FIELDS )
73-
74-
7541@router .get ("/" , response = list [SpeciesSchema ], auth = None )
7642def get_species (
7743 request : HttpRequest ,
@@ -127,9 +93,4 @@ def get_species(
12793 ),
12894 )
12995
130- return list (
131- qs .order_by ("species_code" ).values (
132- * _SPECIES_SCHEMA_FIELDS ,
133- "in_range" ,
134- )
135- )
96+ return qs .order_by ("species_code" )
0 commit comments