Search code examples
pythondjangodjango-modelsjinja2

Sorting Objects By Biggest Attribute Value Django


I am creating an application which will record Athletics events and points. Eventually I want to show on the screen the HOUSES (teams), points, and their overall position. The team with the highest number of points will be number one etc...

My model has a field points which will be updated as results are recorded. I want the model to auto-determine he position of the team based off of the other objects' points. How can I achieve this?

Here is my code: models.py

class House(models.Model):
    name = models.CharField(max_length=255)
    points = models.FloatField(default=0, null=False)
    house_color = models.CharField(max_length=10, null=False, blank=False, default='red')
    position = models.IntegerField(default=4)


    def determine_position(self):
        all_houses_queryset = self.objects.all()
        
   

I've tried to get the index of an ordered queryset on the template but it threw a Value error.

Views.py

def dashboard(request):

    ordered_houses = House.objects.all().order_by('-points').values()
    context = {
        'houses': ordered_houses,
        'range': [1,2,3,4],
    }

    return render(request, 'core/index.html', context)

index.html {% for index, house in houses %}


Solution

  • Just enumerate the items:

    def dashboard(request):
        ordered_houses = enumerate(House.objects.order_by('-points'), 1)
        return render(request, 'core/index.html', {'houses': ordered_houses})

    and work with:

    {% for index, house in houses %}
        <!-- … -->
    {% endfor %}

    Please don't use values, it is a primitive obsession antipattern [refactoring.guru] and prevents exposing logic in the template, and following relations like ForeignKeys.