Django @property computes the model field: FieldError: cannot resolve the keyword

I follow the method used by @Yauhen Yakimovich in this question:

Do properties for django model fields work?

To have a model field, which is a calculation of another model.

Problem:

FieldError: Cannot resolve keyword 'rating' into field. Choices are: _rating 

The rating inst model field is correctly hidden and overridden by the rating property, which causes an error when trying to access it.

My model:

 class Restaurant(models.Model): ... ... @property def rating(self): from django.db.models import Avg return Review.objects.filter(restaurant=self.id).aggregate(Avg('rating'))['rating__avg'] 

The model in Yauhen answers:

 class MyModel(models.Model): __foo = models.CharField(max_length = 20, db_column='foo') bar = models.CharField(max_length = 20) @property def foo(self): if self.bar: return self.bar else: return self.__foo @foo.setter def foo(self, value): self.__foo = value 

Any ideas on how to properly hide the rating field and define the @property method?

UPDATE:

I used a request with order_by() to call rating . order_by() is at the database level and does not know about my property. Soultion, use Python to sort instead:

 sorted(Restaurant.objects.filter(category=category[0]), key=lambda x: x.rating)[:5] 
+4
source share
2 answers

Solved using sorted()

I used the query with order_by () to evaluate the rating. order_by () is at the database level and does not know about my property. Soultion, use Python to sort instead:

 sorted(Restaurant.objects.filter(category=category[0]), key=lambda x: x.rating, reverse=True)[:5] 

If you encounter a similar error, check your views on everything that a property can cause. Properties will no longer work at the database level.

+2
source

Change this line:

 self._rating = Review.objects.filter(restaurant=self.id).aggregate(Avg('rating'))['rating__avg'] 

in that:

 self._rating = Review.objects.filter(restaurant=self.id).aggregate(Avg('_rating'))['_rating__avg'] 

(note the link change in the request from rating and rating__avg to _rating and _rating__avg )

+1
source

Source: https://habr.com/ru/post/1498981/


All Articles