I would like to have a field status on a queryset that is derived from a function of a prefetched set of feedback values.
Example of feedback:
feedback = [
{'action': 0, 'user': 1},
{'action': 1, 'user': 13},
]
If I were writing this on a Serializer I would do this:
def get_status(self, obj):
# Squash all feedback into single status value
fb = obj.feedback.all()
vals = [f.action for f in fb]
if len(vals) == 0:
return 0 # Unconfirmed
if sum(vals) == 0:
return 1 # Confirmed
return 2 # Rejected
However I'd like to move this logic down into my view's queryset to enable ordering on the field.
queryset = Foo.objects\
.prefetch_related('feedback')\
.annotate(status="???")
I'd like to know what set of available query expressions could mimic the logic of the python function get_status above.
.annotate(..)since the database layer does not know about functions. You can try to convert the above to a expression. You by the way do not need.prefetch_related(..)for that.