2011-10-05 31 views
0

我需要根据我的request.GET URL来过滤querySet,它具有字段名称和值。从过滤参数中获取查询集

我的模型:

class AnimalType(Basemodel): 
    name = models.CharField() 
    type = models.ForeignKey(Type) 

class SubAnimalType(Basemodel): 
    name = models.CharField() 
    animaltype = models.ForeignKey(AnimalType) 

class Location(Basemodel): 
    name = models.CharField() 
    country = models.CharField() 

class Animal(Basemodel): 
    name = models.CharField() 
    typeofanimal = models.ForeignKey(SubAnimalType) 
    location = models.ForeignKey(location) 

我会得到像URL "/search/?typeofanimal__animaltype__type__icontains=foo&location__country__iexact=in&food__icontains=hoo"

现在我需要一个通用的函数,它接受ARGS动物模型&过滤PARAMS如下,应该返回过滤querset。

get_filter_from_filter_params(querySet, filter_params): 
    # logic goes here which should filter fields (i.e typeofanimal & location) which are all belongs/related(fk) of the querySet 
    #And should omit the model fields which not belongs to this model(i.e food field) 
    return filtered query set # querySet.filter(typeofanimal__animaltype__type__icontains=foo,location__country__iexact=in) 

我会打电话给上面的方法一样,

SearchForm(request): 
    q = Animal.objects.all() 
    get_filter_from_filter_params(q, request.GET) 

我希望我有共同的足够的信息。我厌倦了model._meta.get_field(name),它只支持本地字段而不考虑FK字段。

我喜欢把这个函数当作通用函数,这样我就可以将这个函数用于不同的模型。

在此先感谢

回答

-1
Animal.objects.filter(**request.GET) 
+0

这里也request.GET中携带参数“food__icontains”这是不属于动物类。因此会出现错误**无法将关键字“食物”解析为字段** –

+0

尽管本身没有安全问题,但按照请求发送使用参数仍然不是一个好主意。 –