Monday, 26 August 2013

Django @property calculating a model field: FieldError: Cannot resolve keyword

Django @property calculating a model field: FieldError: Cannot resolve
keyword

I'm following the method used by @Yauhen Yakimovich in this question:
do properties work on django model fields?
To have a model field that is a calculation of a diffrent model.
The Problem:
FieldError: Cannot resolve keyword 'rating' into field. Choices are: _rating
The _rating model field isnt correctly hidden and overriden by my rating
property causing an error when I try to access it.
My model:
class Restaurant(models.Model):
_rating = models.FloatField(null=True, db_column='rating')
@property
def rating(self):
self._rating =
Review.objects.filter(restaurant=self.id).aggregate(Avg('rating'))['rating__avg']
return self._rating
Model in Yauhen's answer:
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 correctly hid the _rating field and define the
@property technique?

No comments:

Post a Comment