How to retrieve the latest object added (new one) in Django models and display it in the template?

53 views
Skip to first unread message

Byansi Samuel

unread,
Feb 24, 2023, 6:15:05 AM2/24/23
to django...@googlegroups.com

Hey everyone, l got a problem. Am trying to retrieve a single latest object added everytime, and display it in the template.
Below is my codes but;

Help me figure it out the source of the problem in these different instances below 👇

_______________________ issue number 1_______

#Action/models.py
class ActionGame(models.Model):
        name=models.Charfield()
        published=models.DateTimeField()

#Action/views.py
from Action.models import ActionGame

def action (request):
        latest_action=ActionGame.objects.filter(published=published). latest()
Context={ 'latest_action': latest_action }
return....

But it returns *error* :
name 'published' is not defined

____________________ issue number 2________

#Action/models.py
class ActionGame(models.Model):
        name=models.Charfield()
        published=models.DateTimeField()
        class Meta:
              get_latest_by='published'

#Action/views.py
........
latest_action=ActionGame.objects. latest()
.......

#but it returns *error* :
'ActionGame' object is not iterable

Even if I try this:
............
latest_action=ActionGame.objects. latest('published')
.......

#it returns the Same error:
'ActionGame' object is not iterable

But this second issue, the error is referred in #action.html

{% for x in latest _action %}
<p>{{ x.game_name }}</p>
{% endfor %}

Please l need your assistance.

I'm Samuel,
Thanks

Andréas Kühne

unread,
Feb 28, 2023, 7:05:11 AM2/28/23
to django...@googlegroups.com
Se comments below.


Den fre 24 feb. 2023 kl 12:14 skrev Byansi Samuel <samuelb...@gmail.com>:

Hey everyone, l got a problem. Am trying to retrieve a single latest object added everytime, and display it in the template.
Below is my codes but;

Help me figure it out the source of the problem in these different instances below 👇

_______________________ issue number 1_______

#Action/models.py
class ActionGame(models.Model):
        name=models.Charfield()
        published=models.DateTimeField()

#Action/views.py
from Action.models import ActionGame

def action (request):
        latest_action=ActionGame.objects.filter(published=published). latest()
Context={ 'latest_action': latest_action }
return....

But it returns *error* :
name 'published' is not defined


You haven't defined what the value of published is. If you want to get the last created one the query should be:
latest_action=ActionGame.objects.latest("published") - that would give you the last published item. Another way would be:
latest_action=ActionGame.objects.order_by("published").last()
 

____________________ issue number 2________

#Action/models.py
class ActionGame(models.Model):
        name=models.Charfield()
        published=models.DateTimeField()
        class Meta:
              get_latest_by='published'

#Action/views.py
........
latest_action=ActionGame.objects. latest()
.......

#but it returns *error* :
'ActionGame' object is not iterable

Even if I try this:
............
latest_action=ActionGame.objects. latest('published')
.......

#it returns the Same error:
'ActionGame' object is not iterable

But this second issue, the error is referred in #action.html

{% for x in latest _action %}
<p>{{ x.game_name }}</p>
{% endfor %}


So the latest_action variable that you have sent to the template is an instance of ActionGame - and not a list or anything. You can only access variables in the ActionGame class. For example:

 <p>{{ lastest_action.name }}</p>

would print out the value of the name of the ActionGame instance.

Please l need your assistance.

I'm Samuel,
Thanks

--
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/CAGQoQ3wMUno6hLAO-1FtN0Nn7VtkCn4qf-O4U%3DpeJ4JzY%2B%3DcAQ%40mail.gmail.com.

Dev Femi Badmus

unread,
Feb 28, 2023, 9:04:35 AM2/28/23
to django...@googlegroups.com
all_action=ActionGame.objects.all()
my_action = []
for action in all_action:
    my_action.append(action)
last_action = my_action[-1]


Andréas Kühne

unread,
Feb 28, 2023, 11:09:23 AM2/28/23
to django...@googlegroups.com
I'm sorry Dev, but that is really bad practice.

You are doing in python what can be done by the database. That type of code would create a memory error and be very slow to run. It's much better to get the last item from the database. In your example it would just be:
last_action = ActionGame.objects.last()


Michael Starr

unread,
Mar 1, 2023, 3:45:18 PM3/1/23
to Django users
Regarding issue 2, (just to chime in):
You can get all objects to iterate over using a modification of get_context_data(), placed in the relevant view.

def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        context['chosen_variable_name'] = <model object>.objects.all() <-- you can filter here! so: ... .objects.latest("published") or ... .objects.order_by("published").last()
        return context

Then iterate over 'chosen_variable_name' in the template file associated with this view. Remember to choose the association in the view using
template_name = "template to associate to.html"

Michael

Byansi Samuel

unread,
Mar 2, 2023, 3:47:26 AM3/2/23
to django...@googlegroups.com

Hey thanks, but l tried to use ordering=('-published')


Se comments below.


To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

--
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+unsubscribe@googlegroups.com.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAD9bWYwtxjinYmeNWZvBdCdQB5zAa3je1bwMjUhmzEjzF0Q_bg%40mail.gmail.com.

Sandip Bhattacharya

unread,
Mar 2, 2023, 5:29:55 PM3/2/23
to django...@googlegroups.com, Byansi Samuel
Your problem is still about where the 'published’ value is coming from in the call to filter(published=published).

Is it coming from a form? A Get parameter? A post parameter? Extract it appropriately before calling filter()

Boris Pérez

unread,
Mar 2, 2023, 9:43:35 PM3/2/23
to django...@googlegroups.com
One way could be  latest_action=ActionGame.objects.filter(published=published).order_by('-id')[:1]

--
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/A09FDF66-9845-4B93-854D-8BBFC4F5A03D%40showmethesource.org.
Reply all
Reply to author
Forward
0 new messages