python中的for循环获取查询中的第n个元素

2024-03-29 08:51:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如果可以对查询集执行此操作,请检查我下面的python代码:

gp_id= [0,1,2]
for gp in gp_id:
    specail_list = Special.objects.filter(
        promotion=False, 
        start__lte=date_instance, 
        minimum_stay__lte=nights, 
        object_id=room_filter.id, 
        end__gte=date_instance, 
        is_active=True, 
        member_deal=False
    )[gp]
    print specail_list

Tags: instance代码inidfalsefordateobjects
2条回答

我想你可以这样循环:

special_queryset = Special.objects.filter(
    promotion=False, 
    start__lte=date_instance, 
    minimum_stay__lte=nights, 
    object_id=room_filter.id, 
    end__gte=date_instance, 
    is_active=True, 
    member_deal=False
    id__in = gp_id
)
for i in special_queryset:
    print(i)

如果要为queryset中的项更新相同的内容,请使用update()方法。你知道吗

special_queryset.update(promotion=True)

所以我想你是在要求列表中的前三个元素,索引0,1,2。所以,虽然你所做的是有效的,但这种方式更好。你知道吗

切片-每个python程序员应该知道的常见函数:

“切片:https://docs.python.org/3/library/functions.html#slice的Python文档

“限制查询集”的Django文档:

将从未输入的第0个索引开始获取前三个元素。括号也可以是[0:3]。你知道吗

special_list = Special.objects.filter(
    promotion=False, 
    start__lte=date_instance, 
    minimum_stay__lte=nights, 
    object_id=room_filter.id, 
    end__gte=date_instance, 
    is_active=True, 
    member_deal=False
)[:3]

相关问题 更多 >