Note that there are some explanatory texts on larger screens.

plurals
  1. PODifferent results on query changing Q object order
    primarykey
    data
    text
    <p>I have a problem when making a queryset using <code>Q</code> objects. I'm getting different results depending on how i order some <code>Q</code> conditions. I will simplify my models a little so as to describe my problem in a clean way.</p> <pre><code>class D(models.Model): one_attr = models.BooleanField() s_attr = models.ManyToManyField(S, through='DRelatedToS') d_to_p = models.ForeignKey(P) class S(models.Model): other_attr = models.BooleanField() s_to_p = models.ForeignKey(P) class DRelatedToS(models.Model): to_s = models.ForeignKey(S) to_d = models.ForeignKey(D) date = models.DateField() class P(models.Model): the_last_attr = models.PositiveIntegerField() </code></pre> <p>Summary of the relations:</p> <blockquote> <pre><code>D &lt;-- DRelatedToS --&gt; S --&gt; P | ^ | | --------&gt;-------&gt;------&gt;----^ </code></pre> </blockquote> <p>With these models and relations, i get two different results depending on how i arrange Q conditions: <strong>First query, that gives one result</strong></p> <pre><code>D.objects.filter( Q(one_attr=True, s_attr__s_to_p__the_last_attr=5) | Q(one_attr=False, d_to_p__the_last_attr=10) ) </code></pre> <p><strong>Second query, giving another result, different from first query</strong></p> <pre><code>D.objects.filter( Q(one_attr=False, d_to_p__the_last_attr=10) | Q(one_attr=True, s_attr__s_to_p__the_last_attr=5) ) </code></pre> <p>My question is: why is this happening? Is there any problem on how i am doing my query? </p> <p>When i watch the SQL statements derived from these queries, i get two different statements: one that make a <code>LEFT OUTER JOIN</code> and a lot of <code>INNER JOIN</code>s and the second that makes all <code>INNER JOIN</code>s. The one that actually return what i want is the one that makes a <code>LEFT OUTER JOIN</code>. This make me feel that all my queries can return bad results depending on how i arrange its conditions. Is this a bug or i am doing anything (or everything) wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload