I have some models that are laid out like so (with a lot more fields):
class A(models.Model):
name = models.
class B(models.Model):
foo = models.ForeignKey(A)
and I have a search system that uses Q objects; 0 and 1 are primary keys, obtained by a ModelMultipleChoiceField in a form, and both of their foos point to the same A.
So for or logic, I can use this
>>> A.objects.filter(Q(b__pk=0) | Q(b__pk=1))
[<A: A object>, <A: A object>]
and I can fix the duplication by using
A.objects.filter(Q(b__pk=0) | Q(b__pk=1)).distinct()
However, I also want to do and logic. Ideally it would work by using & instead of |, but that doesn’t work.
>>> A.objects.filter(Q(b__pk=0) & Q(b__pk=1))
[]
So, what is the simplest way to do this?
Guess you want A instances that having at least one B() w/ primary key 1 and one B() w/ primary key 0
Then you need
Or the following if join hurts
If you need A() that having only two relative B() one w/ pk=0 and another pk=1, limitation should be applied to the above queryset by