Django 1.6 A.objects.all (). Order_by (['field']) what will django do if the “field” is the default order in the model?

Let's say I have a question model:

class Question(models.Model):
    class Meta:
        ordering = ['title']
    user = models.ForeignKey(User) 
    title = models.CharField()

If you define the order in the Meta, it's just a default setting for entering fewer words, so the figures Question.objects.all().order_by(['title'])and Question.objects.all()will be the same?

+4
source share
1 answer

Yes, the performance is the same. An indication Meta.orderingacts in the same way as an addition order_byto each request.

You can observe the SQL queries that Django generates by setting the DEBUG level for the log django.db.backends.

Examples of models:

class ModelA(models.Model):
    dummy = models.TextField()


class ModelB(models.Model):
    dummy = models.TextField()

    class Meta:
        ordering = ['dummy']

Sample SQL queries:

>>> import logging
>>> l = logging.getLogger('django.db.backends')
>>> l.setLevel(logging.DEBUG)
>>> l.addHandler(logging.StreamHandler())

>>> from sqlorder.models import ModelA, ModelB
>>> ModelA.objects.all()
(0.111) SELECT "sqlorder_modela"."id", "sqlorder_modela"."dummy" 
FROM "sqlorder_modela" LIMIT 21; args=()
[]

ModelA , ModelA.objects.all ORDER BY . .

>>> ModelA.objects.order_by('dummy')
(0.001) SELECT "sqlorder_modela"."id", "sqlorder_modela"."dummy" 
FROM "sqlorder_modela" 
ORDER BY "sqlorder_modela"."dummy" ASC LIMIT 21; args=()
[]

ModelB . , ModelA order_by.

>>> ModelB.objects.all()
(0.001) SELECT "sqlorder_modelb"."id", "sqlorder_modelb"."dummy" 
FROM "sqlorder_modelb" 
ORDER BY "sqlorder_modelb"."dummy" ASC LIMIT 21; args=()
[]

Update: :

$ python manage.py sqlall sqlorder
BEGIN;
CREATE TABLE "sqlorder_modela" (
    "id" serial NOT NULL PRIMARY KEY,
    "dummy" text NOT NULL
)
;
CREATE TABLE "sqlorder_modelb" (
    "id" serial NOT NULL PRIMARY KEY,
    "dummy" text NOT NULL
)
;

COMMIT;
+4

Source: https://habr.com/ru/post/1526134/


All Articles