4

I have a table in PostgreSQL database that contains two columns ID and Name. I am using django framework to get the data from the database and I want to display the data into html page. The problem is that the retrieved data is without columns name. It looks like this, and in order to use it in the html page it has to have a key for each tuple.

[(2, 'abc'), (3, 'subhi')] 

I've tried to get the columns name but they are only table columns without data. Below is my Code:

models.py

import psycopg2
import pprint

def main():
    conn_string = "host='localhost' dbname='music' user='postgres' password='subhi123'"

    column_names = []
    data_rows = []

    with psycopg2.connect(conn_string) as connection:
        with connection.cursor() as cursor:
            cursor.execute("select id, name from music")
            column_names = [desc[0] for desc in cursor.description]
            for row in cursor:
                data_rows.append(row)
                records = cursor.fetchall()

                # print out the records using pretty print
                # note that the NAMES of the columns are not shown, instead just indexes.
                # for most people this isn't very useful so we'll show you how to return
                # columns as a dictionary (hash) in the next example.
                pprint.pprint(records)
                print (type(records))

    print("Column names: {}\n".format(column_names))



if __name__ == "__main__":
    main()

views.py

from django.http import Http404

from django.shortcuts import render
from  .models import main


def index (request):
    all_albums = main()
    return  render(request,'music/index.html',{ 'all_albums' :all_albums})

index.html

{%  if all_albums  %}

<ul>
    {%  for album in all_albums  %}
    <li> <a href="/music/{{ album}}/">{{ album }}</a></li>
    {% endfor %}
</ul>

{% else %}
<h3> You don't have any data</h3>

{%  endif %}

and the settings.py for which shows the PostgreSQL connection:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'music',
        'USER': 'postgres',
        'PASSWORD': 'subhi123',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
2
  • You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which is the well known PostgreSQL connector for Python. You copy/pasted this code from wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL, so follow the advise in comment, and read the next part, titled Select/Fetch Records with Column Names Commented Jun 7, 2018 at 21:43
  • @Antwane how to use the django to retrieve data from DB? I'm beginner to django Commented Jun 7, 2018 at 22:54

2 Answers 2

6

django use ORM(Object-related maping) for db. It's called Model in django.

It means, you should make Model class for your db table and scheme, and django automatically make sql for the model - so you don't do sql job untill you need to.

Below is example of models. (example in docs)

from django.db import models

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

Django create database table like...

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

It's hard to explain all in the answer, so you must look django official docs. After following tutorials (it's well written!), you can understand django - so at least, follow tutorials.

Here's some sites for help.

Sign up to request clarification or add additional context in comments.

Comments

0

You are supposed to use Django module i.e models.py (inherites by django.db.models.Model) this module creates data fields based on your choice and migrate them to the database (in your case Postgresql) when you hit enter by typing in "python manage.py migrate" without string. Possibly due to the fact of this you ain't attaining anything from Database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.