[Answered ]-How do I create a temporary table to sort the same column by two criteria using Django's ORM?

2👍

I believe left join’s may assist in this situation. Your goal is to order cities by the last PM point.

Assuming the primary key of your city table is city_id, and a separate table called city_pm holds the PM points, and that you have two models City and City_Pm…

In your view:

cities = City.objects.all()

In your models:

class City(models.Model):
    # fields ...

    def get_latest_pm(self):
        try:
            return City_Pm.objects.filter(city_id=self.pk).order_by("-date")[:1].get()
        except:
            return None

In your template:

{% for city in cities %}
    {{ city.get_latest_pm }}
{% endfor %}

Leave a comment