Refactoring this Python code to iterate over the container

Surely is there a better way to do this?

results = []
if not queryset is None:
    for obj in queryset:
        results.append((getattr(obj,field.attname),obj.pk))

The problem is that sometimes queryset is None, which throws an exception when I try to iterate over it. In this case, I just want the result to be set to an empty list. This code is from a Django view, but I don't think it matters - this seems like a more general Python question.

EDIT: I get that it was my code that turned the empty request into "No" instead of returning an empty list. Being able to assume that the query is always iterative, simplifies the code by allowing you to remove the if statement. The answers below may be useful for others who have the same problem but cannot change their code to ensure that the request is not "No".

+3
source share
4 answers
results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []]
+19
source

What about

for obj in (queryset or []):
    # Do your stuff

This is the same as the proposal by JF Sebastians, but not implemented as a list comprehension.

+8
source

, Django " " , , None. , , , .

if queryset is None:
    queryset = MyModel.objects.none()

:

+2
source

you can use lists, but other than that I don’t see what you can improve

result = []
 if queryset:
     result = [(getattr(obj, field.attname), obj.pk) for obj in queryset]
+1
source

Source: https://habr.com/ru/post/1702469/


All Articles