Django加入查询

时间:2015-12-17 07:17:44

标签: django django-orm

我有RideVehicle

class Ride(models.Model):
    id = models.AutoField(primary_key=True)

    user = models.ForeignKey(User)
    vehicle = models.ForeignKey(Vehicle, blank=True, null=True, unique=False)
    state = models.CharField(max_length=255, blank=True, null=True)

我想返回一张车辆列表,其中 最后ride.state不等于COMPLETED

有没有办法通过ORM做到这一点?

1 个答案:

答案 0 :(得分:3)

 from django.db.models import Max, F
 Vehicle.objects.annotate(last_ride_id=Max("ride__id")).filter(ride_id=F("last_ride_id").exclude(ride__state="COMPLETE").distinct()

未经测试但应该正常工作

相关问题