Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you run a raw MySQL query in Django without a model?

Tags:

sql

mysql

django

I am still learning Django and I'm just now getting into connectors to MySQL. What I'm trying to figure out is how I would go about querying a db/table that I am not creating with a model in Django.

Do I have to recreate the table as a model in order to have it talk to Django? If so, would that basically mean just recreating my structure with a model then importing my data to the new table?

Sorry if this is a goofy question, I appreciate any help you can give!

like image 894
NTWorthy Avatar asked Nov 22 '19 16:11

NTWorthy


People also ask

Can you use Django without models?

Yes that is possible, but a lot of ways how Django can help with webdevelopment are based on its models. For example based on a model Django can make a ModelForm [Django-doc] to automate rendering HTML forms that map to the model, validating user input, and saving it to the database.

Can we use SQL in Django?

Django has a built-in web server that is used for development purposes. The framework supports several database management systems including Microsoft SQL Server.


1 Answers

Yes, you can query the database table without model by using connection cursor

from django.db import connection

def my_custom_sql(self):
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM table_name where id=1")
    row = cursor.fetchall()
    return row
like image 119
Mukul Kumar Avatar answered Oct 15 '22 19:10

Mukul Kumar