如何从Django中的所有用户中排除一个用户查询集?

2024-05-08 14:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用DRF开发一个django rest api,在我的一个视图中,我覆盖了get_queryset函数:

class UserSearchListView(generics.ListAPIView):

    ...

    def get_queryset(self):
        current_user_friends = Friend.objects.friends(self.request.user)
        all_users = User.objects.all()
        # from the all_users queryset I need to remove the current_user_friends queryset.
        # Should the exclude function be used?

all_users查询集中,我需要排除发出请求的用户和current_user_friends查询集中包含的同一用户的朋友。我该怎么做?在


Tags: thedjango用户selfrestapigetobjects
2条回答

您可以利用values_list和QuerySets的.exclude()方法来实现您的愿望:

current_friends_excluded = all_users.exclude(id__in=current_user_friends.values_list('id', flat=True))

要排除发出请求的用户,可以从请求对象中检索该用户,或者在请求中传递一个标识值来检索该用户,并将其包含在单独的.exclude()中。在

比如:

all_users = [1,2,3,4]
current_user_friends = [1,2]
print list(set(all_users)-set(current_user_friends))
print [user for user in all_users if user not in current_user_friends]
print filter(lambda user: user not in current_user_friends, all_users)

相关问题 更多 >

    热门问题