James L.
James L.

Reputation: 1153

Django 1.6: sort objects by highest values

I've a list of doctors that have a like attribute. I want to list them in my template in descending order based on number of likes they have.

Here is the template where I need to show them

{% for doc in doctors %}
                <h2><a href="/docprofile/{{doc.id}}/">{{doc.name}}</a></h2>
                <h3> {{doc.specialization}}</h3>
                <h4> {{doc.clinic.name}}</h4>
                <h4> {{doc.clinic.address}}</h4>

                <div class="like">
                  <img class="like" src="/static/meddy1/images/like.png">
                  <p>{{doc.likes}}</p>
                </div>

       {% endfor %}
      </div>
    </div>

here is my views.py

@csrf_exempt
def doclistings(request):
    d = getVariables(request)
    doctors = Doctor.objects.all()

    paginator = Paginator(doctors, 20) #Show 20 doctors per page
    page =  page = request.GET.get('page')
    try:
        doctors = paginator.page(page)
    except PageNotAnInteger:
        doctors = paginator.page(1)
    except EmptyPage:
        doctors = paginator.page(paginator.num_pages)
    d['doctors'] = doctors
    d['paginator'] = paginator

    return render_to_response('meddy1/doclistings.html',d)

Upvotes: 0

Views: 44

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39659

Use order_by():

doctors = Doctor.objects.all().order_by('-likes')

You can also define the default ordering in Model Meta class:

class Doctor(models.Model):
    class Meta:
        ordering = ['-likes']

Upvotes: 2

Related Questions