Login

Custom SQL Function; Outputs Template-Friendly Content

Author:
hotani
Posted:
April 28, 2007
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

This will return a template-friendly list of dictionaries when using custom SQL. The dictionary can be accessed just as a normal model/queryset.

Example of use (in view):

qkeys = ['artist','album']
query = """
    SELECT "artist","album" FROM "music"
    """ 
new_list = csql(request,query,qkeys)

(in template)

{% for row in new_list %}
    {{ row.artist }} {{ row.album }}
{% endfor %}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# custom query function:
def csql(self,query,qkeys):
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute(query)
    rows = cursor.fetchall()
    
    # build dict for template:
    fdicts = []
    for row in rows:
        i = 0
        cur_row = {}
        for key in qkeys:
            cur_row[key] = row[i]
            i = i+1
        fdicts.append(cur_row)
    return fdicts

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.