1๐
โ
A return
returns the value, and thus stops the function call. It thus can not return multiple items, or at least not with the return statement.
You can collect all the elements and return a list for example:
def some_brand_mobiles(*brand_names):
if not brand_names:
return Mobile.objects.all()
else:
return [
Mobile.objects.filter(brand__name=brand)
for brand in brand_names
]
then the caller can iterate over the items, so:
for qs in some_brand_mobiles('Apple', 'Huawei', 'Samsung'):
print(qs)
then the output is thus a list that contains a QuerySet
per brand
in the brand_names
.
Beware that we here make n QuerySet
s with n the number of brand_names
. If you later for example print the list, you make n queries, which is not very efficient.
If you simply need all the Mobile
s for a given list of brand_names
, you can work with:
def some_brand_mobiles(*brand_names):
if not brand_names:
return Mobile.objects.all()
else:
return Mobile.objects.filter(brand__name__in=brand_names)
this makes one query, and will return all the relevant Mobile
s in that query.
Source:stackexchange.com