Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading