Loop through QuerySet in Django

33 views
Skip to first unread message

Marcelo A. Robin

unread,
Nov 2, 2022, 12:02:44 PM11/2/22
to Django users
I have a processors.py file where I generate a context processor to load static data into my project's base template. I have posts and I want to generate as a kind of archive in a aside, where you can access through a link, the posts that were created in the month of August 2022 (for example) and that will take me to a page where I will see the entire list of posts. To build that list, from this kind of file, I do the following in the processors.py file:

def ctx_dic_history(request): 
    ctx_history = {} ctx_history['dates'] = Post.objects.dates('created','month').distinct()                        return ctx_history

If I put {{ dates }} in the aside, it returns the following:

<QuerySet [datetime.date(2022, 7, 1), datetime.date(2022, 8, 1), datetime.date(2022, 9, 1), datetime.date(2022, 10, 1)]>

Now I want to go through that queryset, but I can't get what I need: I want them to be sorted descending first, that is, the most recent month on top. Second, I want to access the month and the year, that is, something like "August 2022" appears.

{% for item in dates %} <a href="">Probando</a> {% endfor %}

With that I can iterate over the items that this queryset brings me, but I don't know how to access the date in question for each item in the queryset. If you can give me a hand I would appreciate it in advance. If I manage to get it to work, I'll definitely post the answer that worked for me. Thank you so much

subin

unread,
Nov 3, 2022, 3:40:22 PM11/3/22
to django...@googlegroups.com
Please let me know if that is okay.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/96f58712-88e9-4eae-94f6-909918f2045en%40googlegroups.com.

Marcelo Robin

unread,
Nov 4, 2022, 6:58:57 AM11/4/22
to django...@googlegroups.com
I have a problem 

You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/H1o_Zpd47jk/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJnMy6ch9TUmu01%2BTw65jApLasVXSvMPu7%2BmMKWi6O-BFW10VA%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages