开发者

Easy comparing MySQL plans in Django

开发者 https://www.devze.com 2023-01-03 18:16 出处:网络
is there a way to print out query for example from this line of code Model.objects.all().order_by(sort_headers.get_order_by())

is there a way to print out query for example from this line of code

Model.objects.all().order_by(sort_headers.get_order_by())

I want to plan best way of using Django but with > 开发者_开发问答1 million of objects in my model this is getting too slow.


Two options come to mind:

  1. You can view the raw SQL queries as described in the Django FAQ:

    Make sure your Django DEBUG setting is set to True. Then, just do this:

    >>> from django.db import connection
    >>> connection.queries
    [{'sql': 'SELECT polls_polls.id,polls_polls.question,polls_polls.pub_date FROM polls_polls', 'time': '0.002'}]
    
  2. You could also look at the debugsqlshell supplied as part of the Django Debug Toolbar package. This outputs the underlying SQL for each ORM call that results in a database query, for example:

    >>> from page.models import Page
    >>> ### Lookup and use resulting in an extra query...
    >>> p = Page.objects.get(pk=1)
    SELECT "page_page"."id",
           "page_page"."number",
           "page_page"."template_id",
           "page_page"."description" FROM "page_page" WHERE
    "page_page"."id" = 1
    


Each queryset has a .query reference to the query object. Printing this object will give you the query executed.

>>> f = Model.objects.all().order_by(sort_headers.get_order_by())
>>> print(f.query)
>>> query = str(f.query) # if you want to save it
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号