Getting the SQL from a Django QuerySet

This question already has an answer here:

  • How can I see the raw SQL queries Django is running? 11 answers

  • 您打印queryquery属性。

    >>> queryset = MyModel.objects.all()
    >>> print queryset.query
    SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
    

    Easy:

    print my_queryset.query
    

    For example:

    from django.contrib.auth.models import User
    print User.objects.filter(last_name__icontains = 'ax').query
    

    It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

    from django.db import connections
    connections['default'].queries
    

    The django debug toolbar project uses this to present the queries on a page in a neat manner.


    The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90> .

    The following returned the query:

    >>> queryset = MyModel.objects.all()
    >>> queryset.query.__str__()
    
    链接地址: http://www.djcxy.com/p/38688.html

    上一篇: 需要一个最小的Django文件上传示例

    下一篇: 从Django QuerySet获取SQL