|
1 | | -from django.db.models import Q |
| 1 | +import collections |
| 2 | + |
| 3 | +from django.db.models import F, Q |
| 4 | +from django.db.models.functions import Coalesce |
2 | 5 |
|
3 | 6 | from ..base.coding_system_base import BuilderCompatibleCodingSystem |
4 | 7 | from .models import AMP, AMPP, VMP, VMPP, VTM, Ing |
@@ -47,21 +50,38 @@ def lookup_names(self, codes): |
47 | 50 | # these models first |
48 | 51 | # If not found, look up VTM, VMPP, AMPPs also, in case of user-uploaded codelists that |
49 | 52 | # might contain these |
| 53 | + # |
| 54 | + # If the model type is AMP, we should prefer the `descr` field over the `nm` for the name |
| 55 | + # as this contains the supplier name which helps distinguish AMPs apart. |
| 56 | + # It appears to be populated in 100% of cases but coalese with `nm` just in case it is not. |
50 | 57 | codes = set(codes) |
51 | 58 | lookup = {} |
52 | 59 | for model_cls in [AMP, VMP, AMPP, VMPP, VTM]: |
53 | | - matched = dict( |
54 | | - model_cls.objects.using(self.database_alias) |
55 | | - .filter(id__in=codes) |
56 | | - .values_list("id", "nm") |
| 60 | + model_objs = model_cls.objects.using(self.database_alias).filter( |
| 61 | + id__in=codes |
57 | 62 | ) |
| 63 | + name_field = Coalesce("descr", "nm") if model_cls == AMP else F("nm") |
| 64 | + model_objs = model_objs.annotate(name=name_field) |
| 65 | + matched = dict(model_objs.values_list("id", "name")) |
58 | 66 | for code, name in matched.items(): |
59 | 67 | lookup[code] = f"{name} ({model_cls.__name__})" |
60 | 68 | codes = codes - set(matched.keys()) |
61 | 69 | if not codes: |
62 | 70 | break |
63 | 71 | return lookup |
64 | 72 |
|
| 73 | + def lookup_synonyms(self, codes): |
| 74 | + descriptions = ( |
| 75 | + AMP.objects.using(self.database_alias) |
| 76 | + .filter(id__in=codes) |
| 77 | + .values("id", "nm") |
| 78 | + ) |
| 79 | + |
| 80 | + result = collections.defaultdict(list) |
| 81 | + for d in descriptions: |
| 82 | + result[d["id"]].append(d["nm"]) |
| 83 | + return dict(result) |
| 84 | + |
65 | 85 | def code_to_term(self, codes): |
66 | 86 | lookup = self.lookup_names(codes) |
67 | 87 | unknown = set(codes) - set(lookup) |
|
0 commit comments