python - 返回查询集
问题描述
这是代码:
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 会中断循环并退出函数,即使迭代没有结束,我有两个选项可以产生或将数据附加到列表然后返回列表,但它们都不适合我和我不知道该怎么做,任何帮助将不胜感激
解决方案
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
包含.brand
brand_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。
推荐阅读
- audio - 如何在 swiftUI 中播放来自 http 数据流的音频?
- reactjs - Reactjs 状态变量不更新
- lua - 使用 lua 将字符串变成表情符号
- r - ggplot scale_x_discrete 删除 barplot 中的值
- c# - 统一使用 3d 模型作为按钮
- javascript - Express res.write 不等待一系列承诺完成
- ios - Swift - 制作 CAShapeLayer 发光效果
- javascript - 'CI' 不是内部或外部命令、可运行程序或批处理文件
- unix - 我想在两个路径之一中找到一个具有特定名称的文件。第二个包含一个未知文件夹
- scheduled-tasks - 使用 freeRTOS 通过 systick_Handler 设置 1ms 中断,导致任务只运行一次