我有以下博士后数据库
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 |
===========================================================================================================================
问题
目前没有回答
相关问题 更多 >
编程相关推荐