从GET请求组装数据库查询

时间:2011-12-01 21:16:22

标签: django get

我正在尝试从通过GET请求提供的值组装查询,这是否可能?这是我希望做的一个例子:

def kml(request):
    venues = Venue.objects.filter(
        (Q(neighborhood__city__metro__slug=request.GET.get('metro')) if request.GET.get('metro')),
        (Q(neighborhood__slug=request.GET.get('neighborhood')) if request.GET.get('metro'))
    )
    return HttpResponse(venues)

基本上,如果我去foo.com/?metro=nyc它会返回该大都会区的所有Venue对象。如果我只提供邻居foo.com/?neighborhood=soho,它将返回任何名为Soho的社区的所有场地。最后,foo.com/?metro=nyc&neighborhood=soho将提供满足大都市区和邻里标准的任何场所。

这可能吗?

PS。这基本上是REST api的作用吗?我最好尝试使用Piston,TastyPie或Django-REST吗?

1 个答案:

答案 0 :(得分:1)

Django查询api是chainable,所以你可以这样做:

def kml(request):
    venues = Venue.objects

    if request.GET.get('metro'):
       venues = venues.filter((Q(neighborhood__city__metro__slug=request.GET.get('metro')))

     if request.GET.get('metro')
        venues = venues.filter(Q(neighborhood__slug=request.GET.get('neighborhood')) )

     # and so on...