【问题标题】:how to iterate over a queryset in django as i get 'int' object is not iterable当我得到'int'对象时如何迭代django中的查询集是不可迭代的
【发布时间】:2019-10-09 17:02:00
【问题描述】:

我想从查询集中获取对象

 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)

【问题讨论】:

  • get_external_accounts get 是什么?请提供相关的代码。
  • get_external_accounts 是获取查询集的模型方法,我得到
  • @UmairMohammad 我现在想从上面的查询集中得到 99
  • 很难在没有上下文的情况下设计解决方案,无论如何尝试accounts = group.get_external_accounts(include_sub_groups=True).values_list('id', flat=True)[3]

标签: django python-3.x django-rest-framework django-queryset drf-queryset


【解决方案1】:

顾名思义,.values_list() 返回值的list,而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() 获取单个项目使用accounts.values_list('id') 获取所有ID 的列表将对您的数据库执行两次查询。

如果您有多个具有相同 id 的帐户并想获得第一个,请使用

account: StripeExternalAccount = accounts.filter(id=account_id).first()

【讨论】:

  • 你用的是accounts.get()还是accounts.get(id=account_id)
  • 我使用了accounts.get(id=account_id)
  • 当我使用 account: StripeExternalAccount = accounts.get(account_id) 它给出的 'int' object is not iterable
  • 我更新了我的答案。如果这不能解决您的问题。请编辑您的问题并添加您现在拥有的代码
  • 它有效,但我没有多个具有相同 ID 的帐户
猜你喜欢
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2013-08-02
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多