Django/Python: How to get the latest value from a model queryset?
<p>I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he can update the vehicle location. I wanted to get the latest location for which I did as in my below code. But when i running the server, it returns all the values not the latest value. I would appreciate helping me solve this or suggesting a new approach.</p>

<p>models.py:</p>

<pre><code>class VehicleDetails(models.Model):
    Vehicle_No = models.CharField(max_length=20)

class TripStatus(models.Model):
    vehicledetails = models.ForeignKey(VehicleDetails, related_name='tripstatuss')
    CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata'))
    Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20)
    statustime = models.DateTimeField(auto_now=False, auto_now_add=True)
</code></pre>

<p>views:</p>

<pre><code>def status(request):
    tripstatus = TripStatus.objects.all().latest('statustime')
    context = {
    "tripstatus": tripstatus,
}
    return render(request, 'loggedin_load/active_deals.html', context)
</code></pre>

<p>template:</p>

<pre><code>{% for status in vehicledetails.tripstatuss.all %}
{{status.Vehicle_Status}}
{% endfor %}
</code></pre>

<p>Should just have to remove the .all():</p>

<pre><code>tripstatus = TripStatus.objects.latest('statustime')
</code></pre>

<p>Or maybe:</p>

<pre><code>tripstatus = TripStatus.order_by('-statustime').first()
</code></pre>

python django django-models django-templates django-views