#models.py
class Orders(models.Model):
orderid = models.IntegerField(db_column='orderID', primary_key=True)
createdate = models.DateField(db_column='createDate', blank=True, null=True)
pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)
returndate = models.DateField(db_column='returnDate', blank=True, null=True)
pickupstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='pickupStore', blank=True, null=True,related_name = 'pickupstore')
returnstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='returnStore', blank=True, null=True,related_name = 'returnstore')
rentedvehicle = models.ForeignKey('Vehicles', models.DO_NOTHING, db_column='rentedVehicle', blank=True, null=True)
customer = models.ForeignKey(Customer, models.DO_NOTHING, db_column='customer', blank=True, null=True)
class Vehicles(models.Model):
vehicleid = models.IntegerField(db_column='vehicleID', primary_key=True)
make = models.CharField(max_length=45, blank=True, null=True)
model = models.CharField(max_length=45, blank=True, null=True)
series = models.CharField(max_length=45, blank=True, null=True)
#views.py
def topcar(request):
topCar = Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).annotate(num_car =Count('orders')).order_by('-num_car')[:20]
return render(request, 'web/topcar.html',{'topCar':topCar, 'state':request.POST['state'])
#topcar.html
{% for car in topCar %}
<tr>
<td>{{car.make}} {{car.model}} {{car.series}} {{car.year}}</td>
<td>{{car.seatcapacity}}</td>
<td>{{the latest car return store}}</td>
</tr>
{% endfor %}
在views.py中,topCar变量是Orders模型中具有高订单量的前20个车辆(在Vehicles模型中)的列表.Orders模型中的租车字段是外键,指的是Vehicles模型。
我想获取topCar变量中每辆汽车的最新退货商店(“订单”模型中的字段)。我希望它显示在topCar.html
的{{最新的汽车回收店}}中我应该怎么做?
我发现我可以做到:
Orders.objects.filter(rentedvehicle = car.vehicleid).latest('returndate').returnstore
获取车辆标识符的最新退货存储。但是,我不知道如何使用它来获得想要的结果。
答案 0 :(得分:1)
您只能在Django模板中使用简单的查找逻辑,因此您将无法在其中进行latest('returndate')
过滤。
相反,您可以在Vehicle
模型中添加方法以获取最新订单:
class Vehicles(models.Model):
vehicleid = models.IntegerField(db_column='vehicleID', primary_key=True)
make = models.CharField(max_length=45, blank=True, null=True)
model = models.CharField(max_length=45, blank=True, null=True)
series = models.CharField(max_length=45, blank=True, null=True)
def latest_order(self):
return self.orders_set.latest('returndate')
然后,您应该可以将模板修改为:
{% for car in topCar %}
<tr>
<td>{{car.make}} {{car.model}} {{car.series}} {{car.year}}</td>
<td>{{car.seatcapacity}}</td>
<td>{{car.latest_order.returnstore}}</td>
</tr>
{% endfor %}