Raw SQL queries in Django views

后端 未结 4 713
时光说笑
时光说笑 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:22

    It can be done within one query if you are using PostgreSQL. If not, you can change the query accordingly and get the results.

    from django.db import connection
    from app.models import Picture
    
    def results(request):
        with connection.cursor() as cursor:
            query = """
            SELECT count(*) as all_count, 
            count(*) FILTER(WHERE vote = 'yes') as yes_count
            FROM people_person;
            """
            cursor.execute(query)
            row = cursor.fetchone()
            all_count, yes_count = row
    

提交回复
热议问题