django - 我有一个用户 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中是否有任何内置方法?
解决方案
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)
推荐阅读
- javascript - 为什么这个值在 jQuery 中会发生变化?
- r - 如何在 R 中的 plotly 中添加模式栏按钮?
- css - 兄弟文本后的第一元素选择器?
- python - numpy数组与列表列表?
- javascript - for (var key in object) - 返回未定义 - javascript
- python - 从字符串/元组转换 UTC 日期时间
- php - 使用 PHP 从文件中填充 MySQL 数据库
- react-native - SyntaxError: Unexpected token import React Native
- java - 使用 Visual Studio Code Portable 下载 Java 扩展时出现问题
- python - 如何访问二维列表中的元组