Django / Python:如何从模型查询集中获取最新值?

时间:2016-10-03 11:44:09

标签: python django django-models django-templates django-views

我创建了一个模型' VehicleDetails'用户可以在其中填写车辆和其他模型的详细信息“TripStatus”#39;他可以在其中更新车辆位置。我想获得我在下面的代码中所做的最新位置。但是当我运行服务器时,它返回的所有值都不是最新值。我希望帮助我解决这个问题或建议一种新的方法。

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)

的观点:

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

模板:

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

1 个答案:

答案 0 :(得分:0)

只需删除.all():

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

或者也许:

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