﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34811	Queryset filter Q order changed	Edward Villegas-Pulgarin	nobody	"Using filters in order explicitly expressed by user is important because take advantage of indexes.

When apply this query


{{{
TaxInput.objects.all(
                force_visibility=True
            ).filter(
                Q(filling_id=pk, updated_at__gt=last_engine.created_at)
                | Q(filling_id=pk, deleted__gt=last_engine.created_at),
            )
}}}


the MySQL generated query is


{{{
SELECT
  *
FROM
  `taxobjects_taxinput`
WHERE
  ( `taxobjects_taxinput` . `filling_id` = ?
    AND `taxobjects_taxinput` . `updated_at` > ? )
  OR ( `taxobjects_taxinput` . `deleted` > ?
    AND `taxobjects_taxinput` . `filling_id` = ? )
LIMIT
  ?
}}}


But should be 


{{{
SELECT
  *
FROM
  `taxobjects_taxinput`
WHERE
  ( `taxobjects_taxinput` . `filling_id` = ?
    AND `taxobjects_taxinput` . `updated_at` > ? )
  OR ( `taxobjects_taxinput` . `filling_id` > ?
    AND `taxobjects_taxinput` . `deleted` = ? )
LIMIT
  ?
}}}

This change of order create a 10x factor in query time, because this table has index filing_id, and also index (filing_id, deleted).

Using Django 4.2.1 and SafeDelete 1.3.1 (because this is used force_visibility=True in all manager).
"	Bug	closed	Database layer (models, ORM)	4.2	Normal	worksforme	filter, Q		Unreviewed	0	0	0	0	0	0
