【问题标题】:for loop in python to get nth element in a query setpython中的for循环以获取查询集中的第n个元素
【发布时间】:2018-12-04 04:58:49
【问题描述】:

如果可以为查询集执行此操作,请检查我下面的 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

【问题讨论】:

  • 你想用查询集做什么?
  • 如果在 [] 或 1 或 2 上添加 0,我正在尝试获取返回的内容
  • 仍然不清楚这段代码的目的是什么。

标签: python django python-2.7 django-models


【解决方案1】:

所以我认为您正在尝试询问列表中的前三个元素,即索引 0、1、2。因此,虽然您所做的事情是有效的,但这种方式更好。

Slice - 每个 Python 程序员都应该知道的常用函数:

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

“限制查询集”的 Django 文档: https://docs.djangoproject.com/en/2.1/topics/db/queries/#limiting-querysets

将从未输入的第 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]

【讨论】:

  • 谢谢,是的,我已经尝试过了,但它不适用于我的整个代码
  • 也许可以编辑您的问题以显示其不起作用的示例。
【解决方案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)

如果您想为查询集中的项目更新相同的内容,请使用update() 方法。

special_queryset.update(promotion=True)

【讨论】:

    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2022-08-18
    相关资源
    最近更新 更多