Recover database data on Django

Asked

Viewed 58 times

1

My project is a simple table showing countries, number of covid cases, deaths and recoveries. By Django admin I have already registered two countries and now I want to recover this data and show on the route, but is not showing.

Link to the complete project: https://github.com/PUC-DISCIPLINAS/monitorcoviddjango-monitor-django-guilherme-pedro This is my html file: https://github.com/CunhaGuilhermeBR/html/blob/main/index.html

My model, I’m calling data:


# Create your models here.
class Dados(models.Model):
 casos_confirmados =  models.IntegerField()
 mortes = models.IntegerField()
 recuperados = models.IntegerField()
 pais = models.CharField(max_length=100)

 def __int__(self):
     return(self.id)


 class Meta:
     db_table = 'dados'

And this is my view

@login_required(login_url='/login/')
def list_data(request):
    dados = Dados.objects.all()
    print(dados.query)
    for d in dados:
      print(d)
    return render(request, 'index.html',{dados: dados})

What it prints is: Data Object (1) Data Object (2) Remembering that I have two registered countries. I wanted to find out what I am doing wrong.

2 answers

2

To retrieve database values for an html or directly in the console in views

from .models import Dados
#Do model dados
dados = Dados.objects.all()# retorna todos os valores, mesmo são do tipo queryset
for i in list(dados): # para a forma de list e não queryset
   print(i) # valores

The function str(self), within the scope of the model class returns readable values, which can be specified

def __str__(self):
        return f'{self.pais} {self.casos_confirmados} {self.mortes} {self.recuperados}' 

The presentation in an html needs a context, a dictionary;

def list_data(request):
     conteuto = {"casos": Dados.objects.all()}
    return render(request, 'index.html',conteuto)

html:

 {% for caso in casos %}
  informações: {{caso}}
{% endfor %}

That code solves the question

  • Man, thanks a lot, it worked great. Now in theory what I was doing wrong was how I passed the data to html and how did I iterate into html? Thanks again

  • For nothing, anything we are here to try to help. :)

0

Use:

dados = Dados.objects.all().values_list
for d in dados:
   print(d)

Another option is to use the values():

dados = Dados.objects.all().values()

See the possibility to use __str__()
Example of documentation:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)
  • The print on the terminal is now correct, but the data is not yet shown in html. How to proceed? The impression was this : (1, 5, 4, 1, 'Guatemala') (2, 500, 400, 100, 'Japan')

  • Now it prints right, but still not displaying this data on the front. {'id': 1, 'confirmed cases': 5, 'deaths': 4, 'recovered': 1, 'parents': 'Guatemala'} {'id': 2, 'confirmed cases': 500, 'deaths': 400, 'recovered': 100, 'parents': 'Japan'}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.