Joelad
Joelad

Reputation: 490

How do you get the max value for a foreign key value in models.py file?

This is my html file

{% for member in member_list %}
    {% for batting in batting_list %}
        {% if member.id == batting.member.id %}
            {{ batting }}
            <br>
            {{ batting.match.id }}
            <br>
            {{ batting.runs }}
            <br>
            <hr>
        {% endif %}
    {% endfor %}
{% endfor %}

This is my models.py file


class Member(models.Model):
    name = models.CharField(max_length=40, default='')

    def __str__(self):
        return str(self.name)


class Batting(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE, default='')
    runs = models.IntegerField(blank=True, null=True)
    match = models.ForeignKey(Match, on_delete=models.CASCADE, default='')

    def __str__(self):
        return str('{0} {1} scored {2} runs'.format(self.member, self.match.date, self.runs))

I am trying to figure out how I show the max runs for a member x in the html file. Currently I have been able to do it for the whole Batting table but not for the individual member! Any help please

Upvotes: 2

Views: 565

Answers (3)

Dan Yishai
Dan Yishai

Reputation: 772

You can use annotate over members to get their batting with highest runs value.

from django.db.models import Max
Member.objects.annotate(max_runs=Max("batting_set__runs"))

Then show {{ member.max_runs }} on your template.

Upvotes: 2

Mur4al
Mur4al

Reputation: 121

You need to create annotation in your queryset which will contain highest runs for a member.

from django.db.models import Max

Member.objects.annotate(max_runs=Max('batting__runs'))

You can access it like a regular field

member_object.max_runs

I'm not sure about your view, but for a ListView the class will look like this

class MemberView(ListView):
    template_name = 'tmp.html'
    model = Member

    def get_queryset(self):
        return Member.objects.annotate(max_runs=Max('batting__runs')).all()

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can query with:

from django.db.models import Max

member.batting_set.aggregate(
    max_runs=Max('batting__runs')
)['max_runs']

This will be None if no related Battings exist.

You can annotate the Members queryset with:

from django.db.models import Max

member_list = Member.objects.annotate(
    max_runs=Max('batting__runs')
)

and thus then render this with:

{% for member in member_list %}
    {{ member.max_runs }}
{% endfor %}

Upvotes: 3

Related Questions