简体   繁体   English

Django REST Framework:使用组合过滤器从另一个查询集中排除一个查询集

[英]Django REST Framework: Exclude one queryset from another with combined filters

I have the following method which return objects for is_active=True and for particular user. 我有以下方法返回is_active=True和特定用户的对象。

def filter_active_user(self, queryset, name, value):
    return queryset.filter(active_states__is_active=True,
                           active_states__user_id=value)

I would like to build a method which will return a queryset with all the objects which are not included in the above method. 我想构建一个方法,该方法将返回一个查询集,其中包含上述方法中未包含的所有对象。 So I created the following method using exclude : 因此,我使用exclude创建了以下方法:

def filter_inactive_user(self, queryset, name, value):
    return queryset.exclude(active_states__is_active=True,
                            active_states__user_id=value)

I also tried the following implementation using ~Q : 我使用也尝试下面的实现~Q

def filter_inactive_user(self, queryset, name, value):
    return queryset.filter(~Q(active_states__is_active=True,
                              active_states__user_id=value))

But, I don't get the correct results. 但是,我没有得到正确的结果。 For example in a test case, I have created some data, consisted of 3 objects. 例如,在一个测试案例中,我创建了一些数据,该数据由3个对象组成。 Using the method filter_active_user I'm getting 1 object and I expect to get the other 2 using the filter_inactive_user method, but I'm getting also 1. To be more specific below presented my test data: 使用方法filter_active_user我得到1个对象,我希望使用filter_inactive_user方法得到另外2个对象,但是我也得到1。下面更具体地介绍我的测试数据:

record_1.set_active_states_for_users([self.user1.uuid], True)
record_2.set_active_states_for_users([self.user1.uuid], False)
record_2.set_active_states_for_users([self.user2.uuid], True)
record_3.set_active_states_for_users([self.user2.uuid], False)

When I'm using the the filter_active_user for user=user2 I'm getting the record_2 . 当我将filter_active_user用于user=user2我得到了record_2 When I'm using the filter_inactive_user for user=user2 I'm getting only the record_1 and not the record_3 . 当我将filter_inactive_user用于user=user2我只获得了record_1而不是record_3 Can you help me to build the properly way to combine two filters in a queryset? 您能帮我建立在查询集中组合两个过滤器的正确方法吗?

Solution 1: 解决方案1:

def filter_inactive_user(self, queryset, name, value):
    qs_active = queryset.filter(active_states__is_active=True, active_states__user_id=value)
    qs_inactive = queryset.exclude(pk__in=qs_active.values_list('pk', flat=True))

Solution 2: 解决方案2:

def filter_inactive_user(self, queryset, name, value):
    qs_inactive = queryset.exclude(active_states__is_active=True).exclude(active_states__user_id=value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM