Django annotation from different sources
I'm trying to build following annotation, essentially looking up the nin
field from a person either from the IDcard
or from the Person
model.
.annotate(
checkins_scan=Scan.objects.filter(models.Q(nin=OuterRef("person__idcard__nin") | models.Q(national_number=OuterRef("person__nin")))
.values(
data=JSONObject(id="id", nin="nin", datetime="datetime")
)[:1]
)
However, I get following error:
NotImplementedError: Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations.
Looks like I'll need bitor()
, but I'm not getting any further with the basic examples I'm finding (e.g. documentation here).
When I try to work with F()
I get TypeError: F.__init__() got an unexpected keyword argument 'nin'
.
Any clues on how to properly do this?
You need to use a Subquery
[Django-doc], and the parenthesis did not fully match.:
from django.db.models import OuterRef, Subquery
MyModel.objects.annotate(
checkins_scan=Subquery(
Scan.objects.filter(
models.Q(nin=OuterRef('person__idcard__nin'))
| models.Q(national_number=OuterRef('person__nin')).values(
data=JSONObject(id='id', nin='nin', datetime='datetime')
)
)[:1]
)
)
the |
operator cannot be used in certain ORM contexts like OuterRef
and Subquery
. Instead, you must use Q().bitor(Q())
to achieve the same effect.
checkins_scan = (
Scan.objects.filter(
Q(nin=OuterRef("person__idcard__nin")).bitor(Q(national_number=OuterRef("person__nin")))
).values(id="id", nin="nin", datetime="datetime")[:1]
)
.annotate(checkins_scan=Subquery(checkins_scan, output_field=JSONObject()))