如何在django_filter中使用选择字段值过滤对象

时间:2019-01-24 11:01:04

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

我的模型IPInfo中有以下选择字段

class IPInfoModel(models.Model):
    TYPE_INTRANET = 1
    TYPE_INTERNET = 2
    IP_TYPES = (
        (TYPE_INTRANET, u'INTRANET'),
        (TYPE_INTERNET, u'INTERNET'),
    )
    ip = models.GenericIPAddressField("IP", unique=True)
    ip_type = models.SmallIntegerField(choices=IP_TYPES)

并且我使用django_filters过滤IPInfo。

from django_filters import rest_framework as django_filters 

class IPInfoFilter(django_filters.FilterSet):
    ip_type = django_filters.ChoiceFilter(choices=IPInfoModel.IP_TYPES)

    class Meta:
        model = IPInfoModel
        fields = ["ip_type",]


class IPInfoViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = IPInfoModel.objects.all()
    serializer_class = IPInfoSerializer
    filter_class = IPInfoFilter

我想过滤ip_type上的IPInfo。如何通过“ INTRANET”或“ INTERNET”过滤IPInfo。不要使用“ 1”或“ 2”。

1 个答案:

答案 0 :(得分:1)

您可以定义represented internally by 7 or 8 bytes

with t as (
     select t.*, 
            sum(case when c is not null then 1 else 0 end) over (partition by cn, gn, sg order by sn) as grp
     from dbo.T as t  
)
select distinct t.CN, t.GN, t.SG, t.SN, t.C, tt.cb
from t cross apply
     ( select ''+t1.cb
       from t t1 
       where t1.cn = t.cn and t1.gn = t.gn and t1.sg = t.sg and t1.grp = t.grp
       for xml path('')
     ) tt(cb)
where t.C is not null;