Django annotate

Is there a way to annotate a field in a model and another model object?

I have a model object Restaurantthat I want to annotate the weight field. My criteria are the number of reviews + the 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 gives an error, and I'm not sure how to fix this. num_visits- field in the model Restaurant. Any help is appreciated.

+4
source share
1 answer

I think you will need something like this

qs = Restaurant.objects.annotate(weight=Count('reviews') + F('num_visits'))
weighted = qs.order_by('weight')

He uses expression F.

+3
source

All Articles