Benji Tan
Benji Tan

Reputation: 685

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

Good Day SO, I am a beginner in Django and python, just started learning two days ago. This qn is related to this question:

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

I have two models in a one(crisis)-to-many(plans) relationship, with the models shown here:

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)

Currently, the displayed data looks something like this:

enter image description here

I am new to django/python in general, and I do not know how to filter the data such that i only display each crisis once, and report ID with the highest value. My desired end result looks like this:

enter image description here

Here is my views.py section:

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))

How do I code the loop function to get the max value of the planID for each crisisID? Any help will be greatly appreciated.. Thank you very much SO..

Upvotes: 2

Views: 1574

Answers (2)

user8060120
user8060120

Reputation:

Also you can try to use annotate

from django.db.models import Max

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

Upvotes: 2

Benji Tan
Benji Tan

Reputation: 685

After some trying, I did something like this:

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)

As i'm new to python programming, I assume this is bad practice if I loop twice without using any inbuilt methods, but it works for now. Sorry for the poor question, cheers

Upvotes: 0

Related Questions