[英]How can I access choices of the model in the serializers and obtain a json view
models.py模型.py
MSI_OPTIONS = (
(ANC1, 'AN1'),
(ANC2, 'AN2'),
(ANC3, 'AN3'),
(ANC4, 'AN4'),
(DELIVERY, 'Delivery'),
(FAMILY_PLANNING, 'Family Planning'),
)
class MSIService(models.Model):
girl = models.ForeignKey(Girl, on_delete=models.CASCADE)
option = models.CharField(choices=MSI_OPTIONS, default=ANC1, max_length=250)
I a'm trying to obtain a JSON object counting how many time each MSI_OPTIONS
is used like我正在尝试获取 JSON object 计算每个MSI_OPTIONS
使用了多少次
{ "ANC1":3, "ANC2":4 "ANC3":4 "ANC4":10 } {“ANC1”:3,“ANC2”:4“ANC3”:4“ANC4”:10}
Note: each girl has one of MSI_OPTIONS
.注意:每个女孩都有一个MSI_OPTIONS
。
What you might be looking for is django-aggregations您可能正在寻找的是django-aggregations
And maybe something like:也许是这样的:
aggregated_result = MSIService.objects.annotate(num_options=Count('option'))
aggregated_result_dict = {
element.girl, element.num_options for element in aggregated_result
}
print(aggregated_result_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.