简体   繁体   中英

Django/Python: How to get the latest value from a model queryset?

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.

models.py:

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)

views:

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

template:

{% for status in vehicledetails.tripstatuss.all %}
{{status.Vehicle_Status}}
{% endfor %}

Should just have to remove the .all():

tripstatus = TripStatus.objects.latest('statustime')

Or maybe:

tripstatus = TripStatus.order_by('-statustime').first()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM