首页 > 解决方案 > 返回查询集

问题描述

这是代码:

def some_brand_mobiles(*brand_names):
    if not brand_names:
        return (Mobile.objects.all())
    else:
        for brand in brand_names:
            return Mobile.objects.filter(brand__name=brand)

的预期输出some_brand_mobiles('Apple', 'Huawei', 'Samsung')

<QuerySet [<Mobile: Apple iphone 8>, <Mobile: Apple iphone 10>, <Mobile: Apple iphone XIII>]>
<QuerySet [<Mobile: Huawei P40>, <Mobile: Huawei P10 Pro>, <Mobile: Huawei P90 Pro>]>
<QuerySet [<Mobile: Samsung A80>, <Mobile: Samsung A70>]>

相反,它只返回这个:

<QuerySet [<Mobile: Apple iphone 8>, <Mobile: Apple iphone 10>, <Mobile: Apple iphone XIII>]>

我知道在循环内使用 return 会中断循环并退出函数,即使迭代没有结束,我有两个选项可以产生或将数据附加到列表然后返回列表,但它们都不适合我和我不知道该怎么做,任何帮助将不胜感激

标签: pythondjangodjango-queryset

解决方案


Areturn返回该值,从而停止函数调用。因此它不能返回多个项目,或者至少不能使用 return 语句。

您可以收集所有元素并返回一个列表,例如:

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
        ]

然后调用者可以遍历这些项目,所以:

for qs in some_brand_mobiles('Apple', 'Huawei', 'Samsung'):
    print(qs)

那么输出因此是一个列表,其中QuerySet包含.brandbrand_names

请注意,我们在这里将n QuerySet设为n的数量brand_names。例如,如果您稍后打印列表,则进行n次查询,这不是很有效。

如果您只需要给Mobile定列表的所有 s brand_names,则可以使用:

def some_brand_mobiles(*brand_names):
    if not brand_names:
        return Mobile.objects.all()
    else:
        return Mobile.objects.filter(brand__name__in=brand_names)

这会进行一个查询,并将返回Mobile该查询中的所有相关 s。


推荐阅读