簡體   English   中英

如何根據django中的forgen鍵集進行反向查詢集

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

它有點復雜,以下是正在執行查詢的 2 個模型:

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)

我在請求中得到一個站點對象,我需要根據它過濾線路模型,如果它是一個開始、結束或在線站點..這是我如何嘗試的:

@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

有什么幫助嗎??

試試這個查詢:

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

如果您還想包括具有to_station_object作為內聯站的線路:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM