gpt4 book ai didi

python /Django : Selecting max value of one-to-many relation and displaying it in HTML/View

转载 作者:行者123 更新时间:2023-12-05 05:19:14 25 4
gpt4 key购买 nike

美好的一天,我是 Django 和 Python 的初学者,两天前才开始学习。这个 qn 与这个问题有关:

Python/Django: How to show both main model and 'foreign-key model' together in HTML

我有两个模型处于一对多(计划)关系中,模型如下所示:

class Plan(models.Model):
plan_ID = models.CharField(
primary_key=True,
max_length=8,
validators=[RegexValidator(regex='^\w{8}$', message='Length has to be 8', code='nomatch')]
)
plan_crisisID = models.ForeignKey(Crisis, on_delete=models.CASCADE)
plan_status = models.CharField(max_length=50)

class Crisis(models.Model):
crisis_ID = models.CharField(
primary_key=True,
max_length=4,
validators=[RegexValidator(regex='^\w{4}$', message='Length has to be 4', code='nomatch')]
)
crisis_name = models.CharField(max_length=50)

目前,显示的数据看起来像这样:

enter image description here

一般来说,我是 django/python 的新手,我不知道如何过滤数据,以便我只显示每个危机一次,并报告具有最高值的 ID。我想要的最终结果如下所示:

enter image description here

这是我的 views.py 部分:

def home(request):
template = loader.get_template('pmoapp/home.html')
planList = Plan.objects.filter(plan_crisisID__crisis_status='Ongoing')

context = {
#'crisisList': crisisList,
'planList': planList
}
return HttpResponse(template.render(context, request))

如何编写循环函数以获得每个 crisisID 的 planID 的最大值?任何帮助将不胜感激..非常感谢..

最佳答案

您也可以尝试使用 annotate

from django.db.models import Max

Plan.objects.values('plan_crisisID__crisis_ID').annotate(max_pk=Max('plan_ID'))

关于 python /Django : Selecting max value of one-to-many relation and displaying it in HTML/View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com