#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)
订单模型具有外键租用的车辆,指的是车辆模型
我已根据取货商店的状态过滤了数据,例如在特定状态下从商店取车的车辆列表
Vehicles.objects.filter(orders__pickupstore__state = request.POST['state'])
我希望能够过滤上面过滤的数据,这样我就可以获得在特定状态下从商店取回的车辆的列表,其最新输入在Orders模型中具有returnstore__state ==特定状态
所以基本上,我想实现这一点:
Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).filter(the latest entry returnstore state =request.POST['state'])
答案 0 :(得分:1)
许多可能的解决方案。最佳取决于您的Django版本(1.11或更高版本?)。这是一种可能的解决方案:
from django.db.models import Max, F
Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).annotate(max_date=Max('orders__returndate')).filter(orders__return_date=F('max_date')).filter(orders__state = request.POST['state'])
这里发生的事情是,我们要确定最近的退货日期,然后过滤订单以仅包括最新的退货日期,然后根据最新订单的状态过滤车辆。