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]
source share