我需要根据我的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)
我会得到像"/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字段。
我喜欢将此函数作为通用函数,以便我可以将此函数用于不同的模型。
提前致谢
答案 0 :(得分:-1)
Animal.objects.filter(**request.GET)