我试图从乘客路线的ManyToMany关系中获得乘坐(一)。
以下是模型
class Route(models.Model):
"""
Route model for Retrive a Route M FROM GOOGLE API
"""
user = models.ForeignKey(User, related_name='route')
car = models.ForeignKey(Car, related_name='car', null = True, default= None)
status = models.BooleanField(default = True)
on_ride = models.BooleanField(default = False)
class Ride(models.Model):
"""
Ride model for manage the optimized Route
"""
seats_available = models.PositiveSmallIntegerField(default = 0)
d_route = models.ForeignKey(Route, related_name= 'd_route')
p_route = models.ManyToManyField(Route, related_name= 'p_route',blank = True)
这是我的观点,如果我发送了一个d_route(驾驶员路线)ID我可以检索Ride但是如果我尝试使用p_route(乘客路线),则服务器返回Ride匹配查询不存在。
这是视图
class RideOrRoute(APIView):
# authentication_classes = (TokenAuthentication,)
permission_classes = () # (IsAuthenticated,)
def get(self, request, route_id):
route = Route.objects.get(id = route_id)
try:
ride= Ride.objects.get(d_route = route)
serialized_data = {'id': ride.id ,'geocoded_waypoints': json.loads(ride.geocoded_waypoints), 'routes': json.loads(ride.routes) }
return Response(serialized_data, status= status.HTTP_200_OK)
except:
try:
ride = Ride.objects.get(p_route = route.id)
serialized_data = {'id': ride.id ,'geocodedwaypoints': json.loads(ride.geocoded_waypoints), 'routes': json.loads(ride.routes) }
return Response(serialized_data, status= status.HTTP_200_OK)
except:
serialized_data= {'id': route.id ,'geocoded_waypoints': json.loads(route.geocoded_waypoints), 'routes': json.loads(route.routes) } #json.loads(request_data.read()) })
return Response(serialized_data, status=status.HTTP_200_OK)
请注意,如果驾驶员没有乘车但我只检索路线信息
答案 0 :(得分:1)
我认为您的代码中存在错误。 尝试更改
ride = Ride.objects.get(p_route = route.id)
到
ride = Ride.objects.get(p_route = route)