[Django]-Refactor this Python code to iterate over a container

19👍

results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []]
👤jfs

8👍

How about

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

It is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.

2👍

For what it’s worth, Django managers have a “none” queryset that you can use to avoid gratuitous None-checking. Using it to ensure you don’t have a null queryset may simplify your code.

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

References:

1👍

you can use list comprehensions, 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]

Leave a comment