为多个模型重用Django_filter

时间:2017-04-27 14:08:46

标签: django django-rest-framework django-filter

我有一个非常基本的过滤器设置(使用django-filter),这允许我使用日期范围从我的django rest api查询我的数据:

/api/v2/metrics/?date=2017-01-01
/api/v2/metrics/?start=2017-03-03&end=2017-04-01
/api/v2/metrics/?start=2017-03-03
etc.

我的过滤器看起来像这样:

class DateFilter(filters.FilterSet):
start = filters.DateFilter(name='date', lookup_expr='gte')
end = filters.DateFilter(name='date', lookup_expr='lte')
    class Meta:
        model = GaData
        fields = ['date']

我的API视图集是:

class GaDataViewSet(viewsets.ModelViewSet):
    queryset = GaData.objects.all()
    serializer_class = GaDataSerializer
    filter_class = DateFilter

    def get_queryset(self): # This returns metrics only for the logged in user
        user_id = self.request.user.id
        return GaData.objects.filter(owner=user_id)

class CountriesViewSet(viewsets.ModelViewSet):
    queryset = GaCountries.objects.all()
    serializer_class = GaCountriesSerializer

    def get_queryset(self): # This returns metrics only for the logged in user
        user_id = self.request.user.id
        return GaData.objects.filter(owner=user_id)

现在,DateFilter链接到GaData模型,我可以重新编写一个相同的过滤器并将其链接到我的其他模型(GaCountries),但我认为必须有更好的方法,所以我不需要为每个模型编写相同的代码。

如何为多个模型使用过滤器,或者我可以简单地以某种方式覆盖模型?

由于

1 个答案:

答案 0 :(得分:3)

我通常会为这些情况创建基本过滤器类

class BaseDateFilter(filters.FilterSet):
    start = filters.DateFilter(name='date', lookup_expr='gte')
    end = filters.DateFilter(name='date', lookup_expr='lte')

class GaDataFilter(BaseDateFilter):
    class Meta:
        model = GaData

class GaCountriesFilter(BaseDateFilter):
    class Meta:
        model = GaCountries