DaynaJuliana
DaynaJuliana

Reputation: 1164

Django Joins Query

I have a Ride and Vehicle table where

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)

I want to return a list of vehicles, where their LAST ride.state is NOT equal to COMPLETED

Is there a way to do this via the ORM?

Upvotes: 2

Views: 54

Answers (1)

Ramast
Ramast

Reputation: 7709

 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()

not tested but should work

Upvotes: 3

Related Questions