Reputation: 3447
Is there a way to annotate by a field within the model and another model object?
I have a Restaurant
model object that I want to annotate a 'weight' field. My criteria is number of reviews + number of visits. I would like to do something like this:
weighted = Restaurant.objects.annotate(
weight = Count('reviews') + num_visits??).order_by('weight')
The num_visits part is giving an error and I'm not sure how to correct this. num_visits
is a field in the Restaurant
model. Any help is appreciated.
Upvotes: 4
Views: 474
Reputation: 362716
I think you'll need something like this
qs = Restaurant.objects.annotate(weight=Count('reviews') + F('num_visits'))
weighted = qs.order_by('weight')
It's making use of an F
expression.
Upvotes: 3