[英]Django REST Framework: How to combine two querysets?
I'm trying to combine two filters which are referred to a FK in an object but I'm getting wrong and redundant data. 我试图在对象中组合两个被称为FK的过滤器,但出现错误和冗余数据。
Below presented the filters, located in views.py: 下面显示了位于views.py中的过滤器:
class RecordFilter(df.FilterSet):
user = df.CharFilter(name='active_states__user', method='filter_user')
activestate = df.BooleanFilter(name='active_states__is_active', method='filter_is_active')
class Meta:
model = Record
fields = ['type', 'group', 'user', 'activestate']
def filter_user(self, queryset, _, value):
return queryset.filter(active_states__user_id=value)
def filter_is_active(self, queryset, _, value):
return queryset.filter(active_states__is_active=value)
For example in my test case I created 4 record objects and I added to them activestate and user. 例如,在我的测试案例中,我创建了4个记录对象,并向它们添加了activestate和user。
record1.set_active_states_for_users([user1.uuid], True)
record2.set_active_states_for_users([user1.uuid], False)
record2.set_active_states_for_users([user2.uuid], True)
record3.set_active_states_for_users([user2.uuid], False)
I tried to test these filters for user=user2 and activestate=True. 我尝试为user = user2和activestate = True测试这些过滤器。 And I'm getting: 我得到:
The result should be only the record2. 结果应仅为记录2。
I noticed that the chain
could do the concatenation of the querysets, but I don't know how can I use it in my views.py in class RecordFilter. 我注意到该chain
可以进行查询集的串联,但是我不知道如何在RecordFilter类的views.py中使用它。 Do you have any clue? 你有什么线索吗?
You have situation described here . 您这里描述的情况。 It is possible to implement this API: 可以实现此API:
class RecordFilter(df.FilterSet):
active_user = df.CharFilter(method='filter_active_user')
disabled_user = df.CharFilter(method='filter_disabled_user')
class Meta:
model = Record
fields = ['type', 'group', 'user']
def filter_active_user(self, queryset, name, value):
return queryset.filter(active_states__is_active=True,
active_states__user_id=value)
def filter_disabled_user(self, queryset, name, value):
return queryset.filter(active_states__is_active=False,
active_states__user_id=value)
So you can filter both any, only disabled and only enabled users. 因此,您可以过滤任何,仅禁用和仅启用的用户。 Query active_user=user2 will return just record2. 查询active_user = user2将仅返回record2。
But I don't know why do you use CharFilter
for user
and filter queryset like active_states__user_id=value
. 但是我不知道为什么要对user
使用CharFilter
并像active_states__user_id=value
这样对CharFilter
进行过滤。 Looks like mistake if id
is not a string. 如果id
不是字符串,则看起来像是错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.