Django python:优化db postgresql查询

2024-05-16 21:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下博士后数据库

class Prescription(TimeStampedModel):
    name = models.CharField()
    patient_name = models.CharField()

class PrescriptionLine(TimeStampedModel):
    prescription = models.ForeignKey(Prescription, related_name="prescriptionlines")
    pill = models.ForeignKey(Pill, related_name='prescriptionlines')
    quantity = models.IntegerField()

class Pill(TimeStampedModel):
    pill_category = models.ForeignKey(PillCategory, related_name='pills')

class PillCategory(TimeStampedModel):
    name = models.CharField()

提取数据的代码

def export_on_excel(modeladmin, request, queryset):
    ps = {}
    for p in queryset.prefetch_related('plines'):
        p_detail = {}
        for pline in p.prescriptionlines.all():            
            p_detail[pline.pill.pill_category.name] = pline.quantity
            p_detail['patient_name'] = p.patient_name
        ps[p.name] = p_detail

使用上面的代码,我在字典中提取了3种不同的处方(A、B、C),它们的处方行数不同

ps = {
    Prescription A : {'name': 'A', 'patient_name': 'David', 'pill X': '4g', 'pill Y': '6g', 'pill Z': '10g'},
    Prescription B : {'name': 'B', 'patient_name': 'James', 'pill U': '2g', 'pill X': '6g', 'pill Z': '3g'},
    Prescription C : {'name': 'C', 'patient_name': 'Mary', 'pill S': '2g', 'pill T': '6g', 'pill Y': '3g', 'pill Z': '4g'}
}

上述数据应按下表用以下代码打印到excel文件中

df = pd.DataFrame(ps).fillna('')
df.to_excel('prescriptions.xls')

桌子

|              | Prescription A| Prescription B | Prescription C |
| patient_name |     David     |     James      |     Mary       | 
| --------     |:-------------:| --------------:|----------------|
| Pill S       |               |                |       2g       |
| Pill T       |               |                |       6g       |
| Pill U       |               |      2g        |                |
| Pill X       |    4g         |      6g        |                |
| Pill Y       |    6g         |                |       3g       |
| Pill Z       |    10g        |      3g        |       4g       |

===========================================================================================================================

问题

  1. 我觉得提取代码不是一个很好的代码,因为它有“for循环中的for循环”和“太多查询”。对django和算法都是新手。对代码优化有什么建议吗?提前谢谢

Tags: 代码nameformodelsclasspscharfieldrelated