Home > Software design >  read from database and display as dictionary, not list
read from database and display as dictionary, not list

Time:01-28

I've got a simple database with this table structure:

----------------
| A1 | A2 | A3 |
|--------------|
| B1 | B2 | B3 |
| C1 | C2 | C3 |
----------------

Using this function and djangorestframwork:

@api_view(['GET'])
def read(request, source):

    if source not in sources:
        return Response({'error': f'{source} not found', 'allowed sources': sources, 'help': address})

    with connect(f'{source}/news.db') as conn:
        cmd = '''SELECT * FROM newstable'''
        cur = conn.execute(cmd)
        results = cur.fetchall()
        rand_id = randrange(len(results))

        return Response(results[rand_id])

the contant is displayed in json like this:

[
    'B1',
    'B2',
    'B3
]

However, I want to get this:

{
    'A1': 'B1',
    'A2': 'B2',
    'A3': 'B3
}

CodePudding user response:

This is from Django docs:

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

So you can replace this:

results = cur.fetchall()

with this:

results = dictfetchall(cur)

The other option is to use psycopg2.extras.DictCursor.

  •  Tags:  
  • Related