Django外键反向过滤结果

时间:2016-11-21 17:52:42

标签: django django-rest-framework

我的模型如下:

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对象,并且在该日期没有任何关联事件。即只有可用的大厅。

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分: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)