首页 > 解决方案 > 当我得到'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)

标签: djangopython-3.xdjango-rest-frameworkdjango-querysetdrf-queryset

解决方案


顾名思义,.values_list()返回 a listof 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()

推荐阅读