I’m getting trouble with annotate in Django.
I have two models in projects. (just structure)
model A (field:name(char))
model B (field:A(A; related_name="b"), user(user), content(char; null=True))
The data of model B
is just like…
row1 -> A:1, user:2, content:"content1"
row2 -> A:1, user:3, content:"content2"
row3 -> A:1, user:2, content:None
row4 -> A:2, user:1, content:None
row5 -> A:1, user:3, content:None
My intention is a unique value that combines user and content according to the pk of model A
being searched.
If I look up pk:1 of Model A
and the answer I want is 2, and the reason is as follows.
row1 -> A:1, user:2
row2 -> A:1, user:3
So the orginal code was…
A.objects.annotate(count=Count(Concat("b__user", "b__content"), distinct=True)).get(pk=pk)
However, a value error occurs when looking up model A
that is not referenced in model B
. (count:1)
What can should do?