Return 个查询集

Return querysets

这是代码:

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>]>

相反,它 return 仅此:

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

我知道在循环内使用 return 会中断循环并退出函数,即使迭代没有结束,我有两个选项要么生成数据,要么将数据附加到列表,然后 return 列表,但其中 none 对我有用,我不知道该怎么做,我们将不胜感激

A return returns 值,因此 停止 函数调用。因此它不能 return 多个项目,或者至少不能用 return 语句。

您可以收集所有元素和 return 列表,例如:

def some_brand_mobiles(*brand_names):
    if not brand_names:
        return Mobile.objects.all()
    else:
        return <b>[</b>
            Mobile.objects.filter(brand__name=brand)
            for brand in brand_names
        <b>]</b>

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

for <b>qs in</b> some_brand_mobiles('Apple', 'Huawei', 'Samsung'):
    print(qs)

那么输出是一个列表,其中包含 brand_names 中每个 brandQuerySet

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

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

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

这使得一个查询,并将return该查询中的所有相关Mobiles。