Carbon
Carbon

Reputation: 143

Django using custom SQL instead of models to return JSON object to template

I currently am able to retrieve JSON data/object from my models.py and MySQL database and send that JSON object to my template. How would I be able to use custom SQL to retrieve data from MySQL then make it into a JSON object to send to my template. I basically don't want to use models.py at all. Here is what I have in my views.py when I am using models.py:

def startpage(request):
    platforms = Platform.objects.select_related().values('platformtype')
    return render(request, 'HTML1.html', {'platforms_as_json' : json.dumps(list(platforms)),})

This is what I have so far:

def my_custom_sql(self):
    cursor = connection.cursor()
    cursor.execute("SELECT platformtype FROM Platform", [self.Platform])
    row = cursor.fetchone()
    return row

How would I be able to do the same thing except without using models.py and using custom SQL queries within my views? Thank you

UPDATE:

def startpage(request):
    platforms = my_custom_sql()
    return render(request, 'Html1.html', {'platforms_as_json' : json.dumps(list(platforms)), })


def my_custom_sql():
    cursor = connection.cursor()
    cursor.execute("SELECT HWPlatformName FROM hwplatform", None)
    rows = cursor.fetchall()
    return rows

Now I am able to get the data onto my template but I don't believe it is giving me correct JSON format..

Upvotes: 2

Views: 1282

Answers (1)

cwallenpoole
cwallenpoole

Reputation: 81988

If you want instances of the Model, you're looking for the raw method on the objects property.

platforms = Platform.objects.raw('SELECT * FROM Platform')

If you're just looking for content from the server, then you can just return the value from the SQL query:

platforms = my_custom_sql() # Or call my_custom_sql statically.

If you're looking for delayed population, you can put the yield statement into your my_custom_sql function.

Upvotes: 1

Related Questions