Opened 7 years ago

Closed 7 years ago

Last modified 4 years ago

#8389 closed (duplicate)

Q expression with & and | inconsistent

Reported by: Torsten Bronger <bronger@…> Owned by: mtredinnick
Component: Database layer (models, ORM) Version: 1.0-alpha
Severity: Keywords:
Cc: bronger@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


I use Q expressions in my DB query. It doesn't find anything although it should.

Consider the following

from django.db import models
from django.db.models import Q
import django.contrib.auth.models
from django.contrib import admin

class Sample(models.Model):

class SampleSeries(models.Model):
    originator = models.ForeignKey(django.contrib.auth.models.User)
    samples = models.ManyToManyField(Sample, blank=True)

class UserDetails(models.Model):
    user = models.OneToOneField(django.contrib.auth.models.User)
    my_samples = models.ManyToManyField(Sample, blank=True)

import sys
if sys.argv[1] == "runserver":
        user = django.contrib.auth.models.User.objects.get(username="bronger")
    except django.contrib.auth.models.User.DoesNotExist:
        user = django.contrib.auth.models.User(username="bronger", password="12345")
        user_details = UserDetails.objects.get(user=user)
    except UserDetails.DoesNotExist:
        user_details = UserDetails(user=user)
    if not SampleSeries.objects.count():
    print SampleSeries.objects.filter(
        Q(samples__userdetails=user_details) | (Q(originator=user_details.user) & Q(originator=user_details.user)))

It will print


However, if you delete on of the (obviously redundant) "Q(originator=user_details.user)", it does find the one SampleSeries:

[<SampleSeries: SampleSeries object>]

Change History (4)

comment:1 Changed 7 years ago by anonymous

  • milestone set to 1.0
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 7 years ago by mtredinnick

  • Owner changed from nobody to mtredinnick

comment:3 Changed 7 years ago by mtredinnick

  • Resolution set to duplicate
  • Status changed from new to closed

Looks like this and #8439 are the same problem. I'll close this one in favour of the other, since I find the other example easier to follow.

comment:4 Changed 4 years ago by jacob

  • milestone 1.0 deleted

Milestone 1.0 deleted

Note: See TracTickets for help on using tickets.
Back to Top