Django @property计算模型字段:FieldError:无法解析关键字 [英] Django @property calculating a model field: FieldError: Cannot resolve keyword
问题描述
我正在使用@Yauhen Yakimovich在此问题中使用的方法:
I'm following the method used by @Yauhen Yakimovich in this question:
要拥有一个模型字段来计算不同的模型字段
To have a model field that is a calculation of a different model.
FieldError: Cannot resolve keyword 'rating' into field. Choices are: _rating
rating
模型字段inst我的 rating
属性正确隐藏并覆盖了该属性,当我尝试访问它时会导致错误。
The rating
model field inst correctly hidden and overridden by my rating
property causing an error when I try to access it.
我的模型:
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']
Yauhen回答中的模型:
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
关于如何正确隐藏 rating
字段并定义 @property的任何想法 code>技术?
Any ideas on how to correctly hid the rating
field and define the @property
technique?
推荐答案
通过使用 sorted()
我正在使用带有order_by()的查询来调用评分。 order_by()在数据库级别,并且不了解我的属性。 Soultion,请改用Python进行排序:
I was using a query with order_by() to call rating. order_by() is at the database level and doesnt 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 through your views for anything that might be calling the property. Properties will no longer work at the datatbase level.
这篇关于Django @property计算模型字段:FieldError:无法解析关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!