I am making an app that will search for similar drugs using the logic and models that if a drug is in a particular set of classes then other drugs that are in those and only those classes only then it will return those drugs. Here is the relevant code and dummy data -
views.py
class GetSimilarDrugs(APIView):
def get(self, request, format=None):
#import pdb
#pdb.set_trace()
get_req = request.GET.get('drugid', '')
simi_list = []
comp_class = DrugBankDrugEPClass.objects.filter(drug_bank_id = get_req).values_list('epc_id', flat=True).distinct()
for drg_id in DrugBankDrugEPClass.objects.values_list('drug_bank_id', flat = True).distinct():
classtocomp = DrugBankDrugEPClass.objects.filter(drug_bank_id = str(drg_id)).values_list('epc_id', flat=True).distinct()
complist = list(comp_class)
tolist = list(classtocomp)
if complist == tolist:
simi_list.append(drg_id)
return Response({'result':simi_list})
models.py
class DrugBankDrugEPClass(models.Model):
drug_bank = models.ForeignKey(DrugBankDrugs, on_delete=models.CASCADE)
epc = models.ForeignKey(DrugBankEPClass, on_delete=models.CASCADE)
Dummy SQL Data
id | drug_bank_id | epc_id |
+------+--------------+--------+
| 1 | DB12789 | 1 |
| 2 | DB12788 | 2 |
| 3 | DB00596 | 3 |
| 4 | DB09161 | 4 |
| 5 | DB01178 | 5 |
| 6 | DB01177 | 6 |
| 7 | DB01177 | 6 |
| 8 | DB01174 | 7 |
| 9 | DB01175 | 8 |
| 10 | DB01172 | 9 |
| 11 | DB01173 | 10 |
| 12 | DB12257 | 11 |
| 13 | DB08167 | 12 |
| 14 | DB01551 | 13 |
| 15 | DB01006 | 14 |
| 16 | DB01007 | 15 |
| 17 | DB01007 | 16 |
| 18 | DB01004 | 17 |
| 19 | DB01004 | 18 |
| 20 | DB01004 | 17 |
| 21 | DB01004 | 18 |
| 22 | DB01004 | 19 |
| 23 | DB00570 | 20 |
| 24 | DB01008 | 21 |
| 25 | DB00572 | 22 |
| 26 | DB00575 | 7 |
| 27 | DB00577 | 23 |
| 28 | DB00577 | 24 |
| 29 | DB00577 | 25 |
| 30 | DB00576 | 26 |
| 31 | DB00751 | 27 |
| 32 | DB00751 | 28 |
| 33 | DB00750 | 29 |
| 34 | DB00753 | 30 |
| 35 | DB00752 | 31 |
| 36 | DB00755 | 32 |
| 37 | DB00755 | 32 |
| 38 | DB00757 | 33 |
| 39 | DB00756 | 34 |
| 40 | DB00759 | 35 |
| 41 | DB00759 | 36 |
| 42 | DB00759 | 36 |
I am getting the result but the problem is that it iterating through list everytime and thus taking very much time and for lots of data it is really slow. Is there any other way so it can work faster?