2016-11-21 99 views
0

我有一個模型,如下所示:Django的外鍵反向引用篩選結果

class Event(models.Model): 
    name = models.CharField(max_length=50, blank=False, verbose_name="Event name",) 
    date = models.DateField(auto_now=False, auto_now_add=False,) 
    hall = models.ForeignKey(Hall, on_delete=models.CASCADE, null=True, related_name='events',) 

我有一個觀點只是嘗試的結果:

@api_view(('GET',)) 
def get_specific_hall(request, cityId, year = None, month = None, day = None): 

    hall = Hall.objects.filter(city=cityId) 
    testHall = Hall.objects.get(city=cityId) 

    date = year + '-' + month + '-' + day 
    events = [] 

    for event in testHall.events.filter(~Q(date=date)): 
     events.append(event) 

    eventSerializer = EventSerializer(events, many=True)  
    serializer = HallSerializer(hall, many=True) 
    return Response(serializer.data + eventSerializer.data) 

我要的是:我傳遞日期作爲url參數。我想要返回某個特定城市的Hall對象,並且該日期沒有任何關聯的事件。即只有可用的大廳。

我該如何做到這一點?

回答

0

我更新了我的看法如下:

@api_view(('GET',)) 
def get_specific_halls(request, cityId, year = None, month = None, day = None): 


    date = year + '-' + month + '-' + day 

    hall = Hall.objects.all().filter(Q (city=cityId) , ~Q(events__date=date)) 

    serializer = HallSerializer(hall, many=True) 
    return Response(serializer.data)