我正在寻找一个有效的查询集,因为我的代码试图点燃我的数据库。正如您在下面的代码中看到的那样,这些效率太低了。但我不知道如何使用 select_related 和 prefetch_related 将它们有效地更改为小行代码。框架:Django 2.2-------models.py--------class ProjectModel(models.Model): project_name = models.CharField(max_length=100) start_date = models.DateField(blank=True) end_date = models.DateField(blank=True) code = models.CharField(max_length=100, unique=True) get_pharm = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, related_name='get_pharm') get_hospitals = models.ManyToManyField(UserProfile, blank=True) drugs = models.ForeignKey(DrugModels, on_delete=models.CASCADE, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(choices=STATUS, max_length=3, default='on')class SubjectModel(models.Model): project = models.ForeignKey(ProjectModel, on_delete=models.CASCADE) sex = models.CharField(choices=SEX, max_length=1, blank=True) hospital = models.ForeignKey(UserProfile, on_delete=models.CASCADE) age = models.CharField(blank=True, max_length=10) status = models.CharField(choices=STATUS, max_length=3, default='on')class SubjectDateModel(models.Model): whose = models.ForeignKey(SubjectModel, on_delete=models.CASCADE) will_visit_date = models.DateField(blank=True, null=True) visited_date = models.DateField(blank=True, null=True) visit_check = models.BooleanField(default=False)FEELING = ( (1, 'sobad'), (2, 'bad'), (3, 'normal'), (4, 'good'), (5, 'verygood'),)FLAG = ( ('device', 'DEVICE'), ('drug', 'DRUG'), ('side', 'SIDEEFFECT'), ('feel', 'FEELING'), ('pain', 'PAIN'),)DRUG = ( ('yes', 'ATE'), ('no', 'NO'),)我需要在那个细节模板中制作一些图表。所以我为每个字段值创建了很多上下文并将其发送到模板。但是由于这些代码,我的数据库正在燃烧。有什么好主意可以使这些有效吗?
1 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
也许您可以使用Conditional Aggregation尝试这样:
from django.db.models import Count, Case, When, IntegerField
pains = details.datamodel_set.annotate(
pain0=Count(Case(
When(pain=0, then=1),
output_field=IntegerField(),
))
).annotate(
pain1=Count(Case(
When(pain=1, then=1),
output_field=IntegerField(),
))
) # and so on
pains.values('pain0', 'pain1')
添加回答
举报
0/150
提交
取消