E
E
Enter_a_nickname2022-02-08 15:18:19
Django
Enter_a_nickname, 2022-02-08 15:18:19

How to get the latest record from a database and display it in a table?

I use django 4, on one of the pages of the site I have a table that displays data from the database based on the model I built. To display a table in html, I use the django-tables2 library. Here are some of my settings in views.py:

from django.shortcuts import render
from .models import Titles

def analytics(request):
return render(request, 'main/analytics.html', {'analytics':Titles.objects.all()})


These settings allow me to get all the data from the database and add it to the html table, but I need to get only the last record (according to the extreme id number in the database). I tried to replace "all" with "last", but in this case I get the following error: What needs to be fixed to get only the last record?

ValueError: Expected table or queryset, not Titles

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Nesterov, 2022-02-08
@Enter_a_nickname

It is written - the table or queryset is expected, and last returns one record. Most likely - in tables2 there is a separate method for displaying one record, you just need to google it.
However, if you need to solve the problem "on the forehead", then you can do this: But this, IMHO, is shitty code.
Titles.objects.all().order_by('-id')[:1]

D
Dr. Bacon, 2022-02-08
@bacon

ValueError: Expected table or queryset, not Titles
start by understanding the difference between a queryset and a particular record. Also carefully read https://docs.djangoproject.com/en/4.0/ref/models/q...
To solve your problem, you need to read about order_by and slicing
Threat programmers of the toaster are boobies, now don’t give a link to the django docks normally , replace re with ref quickly corrected and now works

Z
zyusifov11, 2022-02-08
@zyusifov11

Titles.objects.all().order_by('-created_at')[0]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question