Raw SQL queries in Django views

后端 未结 4 712
时光说笑
时光说笑 2020-12-01 01:56

How would I perform the following using raw SQL in views.py?

from app.models import Picture

def results(request):
    all = Picture.objects.all         


        
4条回答
  •  时光说笑
    2020-12-01 02:27

    The Django Documentation is really really good. You have basically two options to execute raw SQL. You can use Manager.raw() to perform raw queries which return model instances, or you can avoid the model layer and execute custom SQL directly.

    Using the raw() manager:

    >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
    ...     print p
    John Smith
    Jane Jones
    

    If you want to bypass the model layer directly you can use django.db.connection which represents the default database connection:

    def my_custom_sql():
        from django.db import connection, transaction
        cursor = connection.cursor()
    
        # Data modifying operation - commit required
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        transaction.commit_unless_managed()
    
        # Data retrieval operation - no commit required
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()
    
        return row
    

提交回复
热议问题