Given the Django model below of a car traveling along a certain road with the start and end times:
class Travel(models.Model):
car = models.CharField()
road = models.CharField()
start = models.DateTimeField()
end = models.DateTimeField()
I want to identify the set of cars X that had been in the same road as the target car x for at least m minutes.
How should I obtain the required set of cars X?
My attempt:
So let's say I use filtering to obtain the set of travels T that x had been in.
T <-- Travel.objects.filter(car=x)
I then brute force with:
for t in T:
possible_travels <-- filter Travel.objects with car=/=x, road=t.road, start < t.end, end > t.start
confirmed_travels <-- further filter possible_travels with the overlapping region being at least m minutes long
confirmed_cars <-- confirmed_travels.values('cars').distinct()
However, the problems are:
- It may involve many DB hits by querying in a loop.
- Also, confirmed_cars gives a QuerySet object. So it seems I need to somehow append these QuerySet objects together. I saw other posts doing things like converting to list then appending and finally converting back to QuerySet but some people say it is not a good way, should I be doing something like this?
Are there some better approaches to this? Is a for loop really necessary and can I avoid it entirely?
Edit:
for 2), I guess a way is to extract the car attribute and append into a list, then do .filter(car__in=the_list), it is not a super big issue compared to the rest.