django rest frame work filter a serializer field

时间:2018-12-10 07:12:37

标签: django django-rest-framework

我有Django API及其序列化器和模型... 我使用这样的过滤器:

class OrderFilter(django_filters.FilterSet):

class Meta:
    model = Dealer
    fields = {
        'first_name': ['icontains', 'exact'],
        'last_name': ['icontains', 'exact'],
        'mobile': ['icontains', 'exact'],
        'is_active': ['exact'],
        'agent': ['exact'],
    }

所有这些字段都是Django模型字段,但是在我的序列化程序中,我有一个SerializerMethodField,如下所示:

class DealerListSerializer(serializers.ModelSerializer):

online = serializers.SerializerMethodField()

def get_online(self, obj):
    r = Redis.get_instance().conn
    key = settings.ONLINE_PREFIX.format(obj.id)
    if r.get(key):
        return True
    return False

我想在在线字段上应用过滤器。

class OrderFilter(django_filters.FilterSet):
online = django_filters.rest_framework.BooleanFilter(method='filter_online')

def filter_online(self, queryset, name, value):
    ?????

class Meta:
    model = Dealer
    fields = {
        'first_name': ['icontains', 'exact'],
        'last_name': ['icontains', 'exact'],
        'mobile': ['icontains', 'exact'],
        'is_active': ['exact'],
        'agent': ['exact'],
        'online': ['exact'],
    }

我该怎么办? 谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下功能

def filter_online(self, queryset, name, value):
     list_of_id = queryset.values("id", flat=True)
     r = Redis.get_instance().conn
     true_list = []
     false_list = []
     for id in list_of_id:
       key = settings.ONLINE_PREFIX.format(id)
       if r.get(key):
         true_list.append(id)
       else:
         false_list.append(id)
     if value:
        return querset.filter(id__in=true_list)
     else:
        return queryset.filter(id__in=fasle_list)