在Django中使用foreignn键引用进行过滤

时间:2018-08-01 23:43:29

标签: python django-models django-rest-framework django-views

我有一个观点正在接受查询参数并搜索符合该查询参数的场所。

 cuisine = self.request.query_params.getlist('cuisine', 0)
        if cuisine != 0:
            cuisinelist =[]
            for cuisine in cuisinelist:
                cuisinepk = get_object_or_404(Cuisine, name=cuisine)
                cuisinepk = cuisinepk.pk
                cuisinelist.append(cuisinepk)
                print('this is the cuisine pk')
                print(cuisinepk)
            venuelist = venuelist.filter(Q(cuisine1__in=cuisinelist) | Q(cuisine2__in=cuisinelist))

但这实际上不起作用,我没有得到任何归还的场地。

场地对象中的Cuisine1和Cuisine2看起来像这样。

cuisine1 = models.ForeignKey(Cuisine, on_delete=models.DO_NOTHING, related_name='cuisine1', blank=True, null=True)
    cuisine2 = models.ForeignKey(Cuisine, on_delete=models.DO_NOTHING, related_name='cuisine2', blank=True, null=True)

当我要检查房间内的关系时,我使用此方法。我想知道是否需要这样做?正确的方法是什么?

seatedcapacity = self.request.query_params.get('seatedcapacity',0)
        if seatedcapacity != 0:
            try:
                seatedcapacity = int(seatedcapacity)
            except ValueError:
                return Response(status=status.HTTP_400_BAD_REQUEST)
            rooms = Room.objects.filter(venue=OuterRef('pk'), seatedcapacity__gte=seatedcapacity)
            venuelist = venuelist.annotate(hasseatedcapacity=Exists(rooms))
            venuelist = venuelist.filter(Q(hasseatedcapacity=True) | Q(fullbuyoutseatedcapacity__gte=seatedcapacity))

0 个答案:

没有答案