简体   繁体   中英

Writing python-written SQL code to interact with Django database

Currently, I'm having a Django project that has an API to let users interact with my database. This project is deployed on Google App Engine, connecting to Cloud SQL (MySQL core).

I would like to add some SQL-based functions, written in python, into this project to

  1. perform tasks on the database, such as querying, predicting, calculating, etc.

  2. automate (1)

Currently, I'm thinking of using mysql.connector.connect() to get the database from the Cloud SQL like below

mydb = mysql.connector.connect(  
            host="/cloudsql/project_name:region_name:instance_name",
            user="username",
            password="password",
            database="database",
            port = "3306", # port should not be specified in deployment?   
        )

and after getting the database, I can do whatever SQL logic, written in Python.

Could anybody suggest a way to achieve these? Thanks a lot.

To be able to make raw SQL queries in Django you must first set your database connection information in your Django Settings file like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': '/cloudsql/project_name:region_name:instance_name',
        'PORT': '3306',
    }
}

Then in your file where you want to run the raw SQL you would do the following:

from django.db import connection

def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()

    return row

For more information see the Django documentation here https://docs.djangoproject.com/en/3.0/topics/db/sql/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM