django - 当我得到'int'对象时如何迭代django中的查询集是不可迭代的
问题描述
我想从查询集中获取对象
accounts = group.get_external_accounts(include_sub_groups=True)
try:
account: StripeExternalAccount = accounts.get(account_id)
except StripeExternalAccount.DoesNotExist:
return Response(status=status.HTTP_400_BAD_REQUEST)
我试过这个。它工作正常,但我想通过尝试来做到这一点,除了
account: StripeExternalAccount = None
for acc in accounts:
if acc.id == int(account_id):
account = acc
break
if not account:
return Response(status=status.HTTP_400_BAD_REQUEST)
解决方案
顾名思义,.values_list()
返回 a list
of values 而list
对象没有.get()
方法。如果get_external_accounts
返回一个查询集,您可以简单地在查询.get()
集上使用:
accounts = group.get_external_accounts(include_sub_groups=True)
try:
account: StripeExternalAccount = accounts.get(id=account_id)
except StripeExternalAccount.DoesNotExist:
return Response(status=status.HTTP_400_BAD_REQUEST)
如果您稍后在代码中需要帐户 ID 列表,您可以添加:
account_ids = accounts.values_list('id')
可能值得指出的是,获取单个项目accounts.get()
并获取所有 ID 的列表accounts.values_list('id')
将对您的数据库执行两次查询。
如果您有多个具有相同 id 的帐户并希望获得第一个帐户,请使用
account: StripeExternalAccount = accounts.filter(id=account_id).first()
推荐阅读
- javascript - eval() 函数在计算器项目中不起作用
- python - 在 Python 上运行 Google Cloud DocumentAI 示例代码返回错误 503
- php - Drupal 7 中的异步函数调用
- javascript - f7DatePicker 根据时区选择前一天
- mysql - mysql存储过程计算距离的Laravel 8控制器变量值
- php - 如何仅在 PHP 的 Preg_match_all 中匹配整个单词,编译失败
- automotive - 回滚在汽车软件下载中是如何工作的?
- javascript - 有没有办法在 navmesh 中获得确切的点,以便探路者可以正常工作?
- sql-server - 在复制到另一个表之前检查 SQL 表中缺少的列
- python - IndexError:列表索引超出范围(无法从列表中删除项目)