Django REST Framework - Filtering

后端 未结 2 1698
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 15:00

I want to filter multiple fields with multiple queries like this:

api/listings/?subburb=Subburb1, Subburb2&property_type=House,Apartment,Townhouse,Farm .         


        
2条回答
  •  臣服心动
    2020-12-21 15:29

    filtering on filters on filters is not messy it is called chained filters.

    And chain filters are necessary because sometime there is going to be property_type some time not:

    if property_type:
        qs = qs.filter(property_type=property_type)
    

    If you are thinking there is going to be multiple queries then not, it will still executed in one query because queryset are lazy.

    Alternatively you can build a dict and pass it just one time:

    d = {'property_type:': property_type, 'subburb': subburb}
    qs = MyModel.objects.filter(**d)
    

提交回复
热议问题