我应该写一个代码来查找具有以下条件的那些驾驶员的所有驾驶员(id)和旅行次数(n): n:在这些行程中,汽车模型为x或刨丝器且行程持续时间超过t秒的行程次数。
我的模特:
class Rider(models.Model):
account = GenericRelation(Account, related_query_name='riders')
rating = models.FloatField()
x = models.FloatField()
y = models.FloatField()
class Driver(models.Model):
account = GenericRelation(Account, related_query_name='drivers')
rating = models.FloatField()
x = models.FloatField()
y = models.FloatField()
active = models.BooleanField(default=False)
class RideRequest(models.Model):
rider = models.ForeignKey(Rider, on_delete=models.CASCADE)
x = models.FloatField()
y = models.FloatField()
car_type = models.CharField(max_length=3, choices=car_type_choices)
class Car(models.Model):
owner = models.ForeignKey(Driver, on_delete=None)
car_type = models.CharField(max_length=3, choices=car_type_choices)
model = models.IntegerField()
color = models.CharField(max_length=10)
class Ride(models.Model):
pickup_time = models.IntegerField()
dropoff_time = models.IntegerField()
car = models.ForeignKey(Car, on_delete=models.CASCADE)
request = models.OneToOneField(RideRequest, on_delete=models.CASCADE, null=False)
rider_rating = models.FloatField()
driver_rating = models.FloatField()
我的代码:
drivers = Driver.objects.values('id').annotate(
travel_time=Sum(Case(
When(car__ride__pickup_time__isnull=False,
then=(F('car__ride__dropoff_time') - F('car__ride__pickup_time'))),
default=0
)),
).annotate(
n=Case(
When(Q(travel_time__gt=t) & Q(car__model__gte=n), then=Count('car__ride')),
output_field=IntegerField(),
default=0
)
).values('id', 'n')
当我打印结果时:
<QuerySet [{'id': 1, 'n': 0}, {'id': 2, 'n': 0}, {'id': 2, 'n': 1}, {'id': 3, 'n': 2}, {'id': 4, 'n': 0}, {'id': 5, 'n': 1}, {'id': 5, 'n': 0}]>
这接近真实答案,但仍然需要做更多。例如,我有两个id = 2。它应该是1,并且与之关联的n应该是1(对于id = 2,这两个n之和)
真实结果:
<QuerySet [{'id': 1, 'n': 0}, {'id': 2, 'n': 1}, {'id': 3, 'n': 2}, {'id': 4, 'n': 0}, {'id': 5, 'n': 1}]>