11from rest_framework import serializers
2- from ...models .model_medRule import MedRule
2+ from ...models .model_medRule import MedRule , MedRuleSource
3+ from ..listMeds .models import Medication
34from ..listMeds .serializers import MedicationSerializer
45from ...models .model_embeddings import Embeddings
5- from .. listMeds . models import Medication
6+
67
78class EmbeddingsSerializer (serializers .ModelSerializer ):
89 class Meta :
910 model = Embeddings
1011 fields = ['guid' , 'name' , 'text' , 'page_num' , 'chunk_number' ]
1112
1213
14+ class MedicationWithSourcesSerializer (serializers .Serializer ):
15+ medication = MedicationSerializer ()
16+ sources = EmbeddingsSerializer (many = True )
17+
18+
1319class MedRuleSerializer (serializers .ModelSerializer ):
14- medications = MedicationSerializer (many = True , read_only = True )
15- medication_ids = serializers .PrimaryKeyRelatedField (
16- many = True , write_only = True , queryset = Medication .objects .all (), source = 'medications'
17- )
18- sources = EmbeddingsSerializer (many = True , read_only = True )
19- source_ids = serializers .PrimaryKeyRelatedField (
20- many = True , write_only = True , queryset = Embeddings .objects .all (), source = 'sources'
21- )
20+ medication_sources = serializers .SerializerMethodField ()
2221
2322 class Meta :
2423 model = MedRule
2524 fields = [
26- 'id' , 'rule_type' , 'history_type' , 'reason' , 'label' ,
27- 'medications' , 'medication_ids' ,
28- 'sources' , 'source_ids' ,
29- 'explanation'
30- ]
25+ 'id' , 'rule_type' , 'history_type' , 'reason' , 'label' , 'explanation' ,
26+ 'medication_sources'
27+ ]
28+
29+ def get_medication_sources (self , obj ):
30+
31+ medrule_sources = MedRuleSource .objects .filter (
32+ medrule = obj ).select_related ('medication' , 'embedding' )
33+
34+ med_to_sources = {}
35+ for ms in medrule_sources :
36+ if ms .medication .id not in med_to_sources :
37+ med_to_sources [ms .medication .id ] = {
38+ 'medication' : ms .medication ,
39+ 'sources' : []
40+ }
41+ med_to_sources [ms .medication .id ]['sources' ].append (ms .embedding )
42+
43+ return [
44+ {
45+ 'medication' : MedicationSerializer (data ['medication' ]).data ,
46+ 'sources' : EmbeddingsSerializer (data ['sources' ], many = True ).data
47+ }
48+ for data in med_to_sources .values ()
49+ ]
0 commit comments