I’m doing my studying project. I have 2 models:
class RoutePoint(geo_models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=False, blank=False,
related_name='routepoints')
point = geo_models.PointField()
datetime = models.DateTimeField()
class Travel(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.DO_NOTHING, null=False, blank=False,
related_name='travels')
begin = models.DateTimeField()
end = models.DateTimeField()
First one contains geopoints for vehicle and date and time for vehicle getting there.
Second one countains the begining and the ending of the rides for vehicles.
I’m having some curl request with two fields – start_date
and end_date
, let’s call it some kind request for report.
So, at first I need to get something like this:
SELECT vehicle_id, begin, end
FROM park_travel
WHERE begin > "2022-12-30" AND end < "2023-01-06"
I’ll call it result
.
And after that i need to get something like:
SELECT vehicle_id, point, datetime
FROM park_routepoint
WHERE vehicle_id = result.vehicle_id
AND datetime > result.begin
AND datetime < result.end
And I have to do it without raw sql…
3
Answers
I did it like this:
It worked perfectly fine, thanks to Iqbal Hussain.
You can do this in one query using double underscore notation and
F
expressions:then simply iterate over the
route_points
queryset:You can filter the Travel Queryset:
Now you can use
travel_qs
to retrieve the Points from RoutePoint: