Search code examples
djangopython-3.xdjango-rest-frameworkdjango-querysetdrf-queryset

how to iterate over a queryset in django as i get 'int' object is not iterable


I want to get the object from a queryset

 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)

I have tried this. it works fine but i want to do it through try except

   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)

Solution

  • As its name implies, .values_list() returns a list of values and a list object doesn't have a .get() method. If get_external_accounts returns a queryset, you can simply use the .get() on the queryset:

    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)
    

    If you need the list of account IDs later in your code, you could add:

    account_ids = accounts.values_list('id')
    

    It might be worth pointing out that getting a single item with accounts.get() and getting the list of all IDs with accounts.values_list('id') will perform two queries to your database.

    If you have multiple accounts with the same id and want to get the first one, use

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