How can I retrieve last x elements in Django

I am trying to retrieve the latest 5 posts (by post time) In the views.py, if I try blog_post_list = blogPosts.objects.all()[:5] It retreives the first 5 elements of the blogPosts objects, how can I reverse this to retreive the latest ones?

Cheers


Asked by: Anna171 | Posted: 30-11-2021






Answer 1

blog_post_list = blogPosts.objects.all().reverse()[:5]
# OR
blog_post_list = blogPosts.objects.all().order_by('-DEFAULT_ORDER_KEY')[:5]

I prefer the first.

Answered by: Tess800 | Posted: 01-01-2022



Answer 2

Based on Nick Presta's answer and your comment, try:

blog_post_list = blogPosts.objects.all().order_by('-pub_date')[:5]

Answered by: Alford508 | Posted: 01-01-2022



Similar questions

xml - How to retrieve certain child elements using python and lxml

With lots of help from stack overflow, I managed to get some python code working to process xml files (using lxml). I've been able to adapt it for lots of different purposes, but there is one thing I can't work out. Example XML: <?xml version="1.0" encoding="UTF-8" ?> <TVAMain xml:lang="PL" publisher="Someone" publicationTime="2014-01-03T06:24:24+00:00" version="217" xmlns="urn:tva:met...


Use bool list to retrieve elements from another list - Python

I have this situation: main_list = [12, 10, 30, 10, 11,10, 31] get_indices = [1, 0, 1, 1, 0, 0, 0] What I want to do is, extract elements from main_list according to the boolean value in get_indices. I tried the following but it is not working : result = main_list[bool(get_indices)] print result 10 It should be 12, 30, 10


python - Retrieve elements from a list

I am inserting items in a list and using heapq for the storing the same. Below is my code.. I need to sort the list based on the first column values (ut) and get the top 10 items on my gui. When I try to retrieve data from my list (i.e self.top10ele) using the 'for loop' below I only get 1 row at a time. Also, I am unnable to delete the previous data.. Can someone please guide me what/where I am going wrong?


Python - Tuples - Retrieve unique elements in list of tuples

UPDATE: I went with this: set(item[1] for item in id) Thanks guys, your ideas helped me. I am working with a list of tuples: Using the following line of code as an example. My list can be of any lenght. However, I will always be looking for a given index of my tuples: id = [(9,'Tup','Check'),(10,'Tup','Pyton'),(11,'Not Tup','Stack'),(12,'N...


python - BFS to retrieve elements of values in each order

I tried to solve the problem Binary Tree Level Order Traversal - LeetCode Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7],


python - Retrieve array elements from a list of index

I have an array my_array containing some tuple data. I have another array my_array_values of same length containing some integer values. For each unique value of my_array_values, I want to retrieve a list of values from my_array, that are in the same index as this value in my_array_values. Here is my code and the expected behavior : ...


python - How to retrieve elements from an array

I have an array - a = ['person', 'dog', 'fire hydrant'] How do I get the first element of this array - person and print it


python - Create a list from a text file then retrieve the elements

Because I can't pass multiple arguments with concurrent.futures / ThreadPoolExecutor. In this code : pool.map(get_url, urls) I would like to pass the iterations_file_numbers variable directly into the generated urls variable in the open_url_files() function I tried this way urls = [[line.strip(), iterations_file_number] for line in ...


python - How to retrieve these elements from a webpage?

I have a webpage in HTML with these elements: <div class="content_page"> <a href="/earth" class="nametessera" >earth</a> </div> <div class="content_page"> <a href="/world" class="nametessera" >world</a> </div> <div class="content_page"> <a href="/planet" class="nametessera">planet</a> </div> ... I need to r...


xml - How to retrieve certain child elements using python and lxml

With lots of help from stack overflow, I managed to get some python code working to process xml files (using lxml). I've been able to adapt it for lots of different purposes, but there is one thing I can't work out. Example XML: <?xml version="1.0" encoding="UTF-8" ?> <TVAMain xml:lang="PL" publisher="Someone" publicationTime="2014-01-03T06:24:24+00:00" version="217" xmlns="urn:tva:met...


Retrieve the ranking of elements in various list to compute the weighted average of their ranking scores Python

I have two sorted dictionaries, i.e. they are now represented as lists. I would like to retrieve the ranking position of each element in each of the lists and store it in a variable so that ultimately I can compute the weighted average of the ranking score of each elements in both lists. Here is an example. dict1 = {'class1': 15.17, 'class2': 15.95, 'class3': 15.95} sorted_dict1 = [('cla...


Use bool list to retrieve elements from another list - Python

I have this situation: main_list = [12, 10, 30, 10, 11,10, 31] get_indices = [1, 0, 1, 1, 0, 0, 0] What I want to do is, extract elements from main_list according to the boolean value in get_indices. I tried the following but it is not working : result = main_list[bool(get_indices)] print result 10 It should be 12, 30, 10


python - Retrieve elements from a list

I am inserting items in a list and using heapq for the storing the same. Below is my code.. I need to sort the list based on the first column values (ut) and get the top 10 items on my gui. When I try to retrieve data from my list (i.e self.top10ele) using the 'for loop' below I only get 1 row at a time. Also, I am unnable to delete the previous data.. Can someone please guide me what/where I am going wrong?


Python: how to retrieve some values from the elements of a list?

I have a list of elements like this: mylist=['event_100of1000', 'event_17of1000', 'event_1000of1000',...] How can I extract the "number" of the event only and produce another list, in the likes of: extracted_list=['100','17','1000',...]?


python - What are the different methods to retrieve elements in a pandas Series?

There are at least 4 ways to retrieve elements in a pandas Series: .iloc, .loc .ix and using directly the [] operator. What's the difference between them ? How do they handle missing labels/out of range positions ?


Python - Tuples - Retrieve unique elements in list of tuples

UPDATE: I went with this: set(item[1] for item in id) Thanks guys, your ideas helped me. I am working with a list of tuples: Using the following line of code as an example. My list can be of any lenght. However, I will always be looking for a given index of my tuples: id = [(9,'Tup','Check'),(10,'Tup','Pyton'),(11,'Not Tup','Stack'),(12,'N...


Python TKinter - Retrieve all the ID of all elements in my canvas

How will I retrieve all the tag ID's of all the elements in my canvas Python Tkinter? ANy help would be very much appreciated.


python - BFS to retrieve elements of values in each order

I tried to solve the problem Binary Tree Level Order Traversal - LeetCode Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7],


html - How can I retrieve the page title of a webpage using Python?

How can I retrieve the page title of a webpage (title html tag) using Python?


python - How to retrieve an element from a set without removing it?

Suppose the following: >>> s = set([1, 2, 3]) How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: >>> elem = s.pop() >>> s.add(elem)


sql server - Python: Retrieve Image from MSSQL

I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python import _mssql mssql=_mssql.connect('<ServerIP>','<UserID>','<Password>') mssql.select_db('<Database...


python - Best way to retrieve variable values from a text file?

Referring on this question, I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: var_a: 'home' var_b: 'car' var_c: 15.5 And I need that python read the file and then create a variable named var_a with value 'home', and so on. Example...


python - How to retrieve the selected text from the active window

I am trying to create a simple open source utility for windows using Python that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut. Usage is partially outlined in the following example: The user selects some text using the mouse or the keyboard (in any application window)


python - Retrieve module object from stack frame

Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works: import sys from some_other_module import callers_module assert sys.modules[__name__] is callers_module() (That would be equivalent because I can generate a stack trace in the function for this test case. The imports are there simply to make that example complete an...


How do I retrieve Hotmail contacts with python

How can I retrieve contacts from hotmail with python? Is there any example?


linux - How to retrieve the process start time (or uptime) in python

How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my_process_id -f" and then parse the output. But it is not cool.


python - Retrieve the two highest item from a list containing 100,000 integers

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?


c++ - How do I retrieve program output in Python?

I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to: $version = `java -version`; How would I go about getting the same end result in Python? Does t...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top