首页 > 解决方案 > 我有一个用户 ID 列表,我想检查每个可用的用户 ID,如果没有,我想获取不可用的以下 ID

问题描述

这是我尝试过的代码

staffids = [1,2,4,5,6,7]
# up_obj = UserProfile.objects.filter(userId__in = staffids) #i will explain it below 
flag=0
unknown = []
for x in staffids:
    up_obj = UserProfile.objects.filter(userId=x)
    if up_obj.exists():
       print(up_obj)
    else:
       flag=1
       unknown.append({
          "id": x
       })
 if flag == 1:
    return Response({
       STATUS:False,
       MESSAGE:"User not found",
       DATA:unknown
    })

此代码仅返回可用用户

up_obj = UserProfile.objects.filter(userId__in = staffids)

假设如果用户 ID 3,4 不可用,则此代码返回不带 3,4 的查询集。

如果所有 id 都不存在,我想返回以下 id 不可用或其他的消息...,我已经尝试过,但我正在寻找更好的方法来做到这一点

django中是否有任何内置方法?

标签: djangodjango-modelsormdjango-rest-framework

解决方案


staffids您可以通过以下方式获取所有userId可用字段,而不是对中的每个条目进行查询UserProfile

all_user_ids = list(UserProfile.objects.all().values_list('userId', flat=True))

然后您可以轻松找到两个列表之间的差异,为您提供缺少哪些 id 的信息。

有了它,您可以打印出确切丢失的内容或您想要对该信息执行的任何操作。

staffids = [1, 2, 3, 4, 5, 6, 7]
qs = UserProfile.objects.all()
all_user_ids = list(qs.values_list('userId', flat=True))

if not all_user_ids:
    # do something ...
else:
    missing_ids = list(set(staffids) - set(all_user_ids))
    # do something ...

    for obj in qs:
        print(obj)

推荐阅读