Ahmed Wagdi
Ahmed Wagdi

Reputation: 4401

how to do reverse query set based on forgen key set in django

its a bit complicated, here are the 2 models that am performing the query on :

class Line(models.Model):
    # Relationships
    end_station = models.ForeignKey("stations.station", related_name='line_end_station', on_delete=models.CASCADE)
    starting_station = models.ForeignKey("stations.station", related_name='line_start_Station',
                                         on_delete=models.CASCADE)



class InLineStation(models.Model):
    # Relationships
    line = models.ForeignKey("lines.Line", on_delete=models.CASCADE)
    in_line_station = models.ForeignKey("stations.station", on_delete=models.CASCADE)

am getting a station object in the request and I need to filter the line model based on it , if it's a starting , ending, or in line station.. here is how I tried this :

@api_view(['POST', ])
def do_search_logic(request):
    if request.method == 'POST':
        from_station_id = request.data['from_station_id']
        to_station_id = request.data['to_station_id']
        from_station_object = station.objects.get(id=from_station_id)
        to_station_object = station.objects.get(id=to_station_id)
        Line.objects.filter(Q(starting_station=from_station_object) | Q(end_station=to_station_object) | Q(from_station_object in inlinestations_set)) #this_is_the_tricky_line

any help about this ??

Upvotes: 0

Views: 42

Answers (1)

Alain Bianchini
Alain Bianchini

Reputation: 4181

Try this query:

Line.objects.filter(Q(starting_station=from_station_object) | Q(end_station=to_station_object) | Q(inlinestations_set__in_line_station=from_station_object))

If you want also to include lines that have to_station_object as inline station:

Line.objects.filter(Q(starting_station=from_station_object) | Q(end_station=to_station_object) | Q(inlinestations_set__in_line_station=from_station_object) | Q(inlinestations_set__in_line_station=to_station_object))

Upvotes: 1

Related Questions