Opened 9 years ago

Closed 9 years ago

Last modified 5 years ago

#8389 closed (duplicate)

Q expression with & and | inconsistent

Reported by: Torsten Bronger <bronger@…> Owned by: Malcolm Tredinnick
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 9 years ago by anonymous

milestone: 1.0

comment:2 Changed 9 years ago by Malcolm Tredinnick

Owner: changed from nobody to Malcolm Tredinnick

comment:3 Changed 9 years ago by Malcolm Tredinnick

Resolution: duplicate
Status: newclosed

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 5 years ago by Jacob

milestone: 1.0

Milestone 1.0 deleted

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