Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python/Django:选择一对多关系的最大值并在HTML/View中显示_Python_Django - Fatal编程技术网

Python/Django:选择一对多关系的最大值并在HTML/View中显示

Python/Django:选择一对多关系的最大值并在HTML/View中显示,python,django,Python,Django,你好,我是Django和python的初学者,两天前刚开始学习。本qn与此问题相关: 在一对多(危机)关系中,我有两个模型,如下所示: class Plan(models.Model): plan_ID = models.CharField( primary_key=True, max_length=8, validators=[RegexValidator(regex='^\w{8}$', message='Length has to

你好,我是Django和python的初学者,两天前刚开始学习。本qn与此问题相关:

在一对多(危机)关系中,我有两个模型,如下所示:

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)
当前,显示的数据如下所示:

for crisis in crisisList:
    plansInCrisis = planList.filter(plan_crisisID__crisis_ID=crisis.crisis_ID)
    max = plansInCrisis[0]
    for plan in plansInCrisis:
        if(plan.plan_ID > max.plan_ID ): max = plan
    toDisplay.append(max)

一般来说,我不熟悉django/python,我不知道如何过滤数据,以便只显示每个危机一次,并使用最高值报告ID。我期望的最终结果如下所示:

for crisis in crisisList:
    plansInCrisis = planList.filter(plan_crisisID__crisis_ID=crisis.crisis_ID)
    max = plansInCrisis[0]
    for plan in plansInCrisis:
        if(plan.plan_ID > max.plan_ID ): max = plan
    toDisplay.append(max)

以下是my 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))

如何对循环函数进行编码以获得每个CrisiId的planID的最大值?任何帮助都将不胜感激。。非常感谢..

经过一番尝试,我做了如下事情:

for crisis in crisisList:
    plansInCrisis = planList.filter(plan_crisisID__crisis_ID=crisis.crisis_ID)
    max = plansInCrisis[0]
    for plan in plansInCrisis:
        if(plan.plan_ID > max.plan_ID ): max = plan
    toDisplay.append(max)
由于我是python编程新手,我假设如果我在不使用任何内置方法的情况下循环两次,这是一种不好的做法,但目前它仍然有效。很抱歉问了这么差的问题,干杯!您也可以尝试使用


我要试试这个!自学当你有最后期限时,这很难。谢谢你的帮助!