Retrieve a list of matching objects from a range of ids in Django

后端 未结 1 1229
清酒与你
清酒与你 2021-01-22 18:54

I want to achieve something relatively simple: I want to retrieve all objects from my model given a range of ids (for eg, retrieve the lines 5 to 10 from a book\'s chapter).

相关标签:
1条回答
  • 2021-01-22 19:12

    I think you want __range:

    Range test (inclusive).

    Example:

    start_date = datetime.date(2005, 1, 1)
    end_date = datetime.date(2005, 3, 31)
    Entry.objects.filter(pub_date__range=(start_date, end_date))

    SQL equivalent:

    SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';

    You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.

    So yours would be, I think:

    chapter_lines = get_list_or_404(..., line__range=(int(line_start), int(line_end)+1))
    

    Likewise, you can use __lt, __gt, __lte, __gte for one-sided comparisons.

    I would encourage you to always keep a window open with the Django documentation. There is lots of great info there if you just look.

    0 讨论(0)
提交回复
热议问题