类元获得无效属性 [英] Class meta got invalid attributes
问题描述
请详细研究后,请放心修改此Meta类的价值。
当我尝试使用get_absolute_url处理模板url时,我收到错误,因为它响应以下错误。
Please help to fix this Meta class value as I gave up after detailed research. I am getting back error while trying to handle template urls with "get_absolute_url" as it responds with following error.
TypeError: 'class Meta'得到无效的属性:sale_price,get_absolute_url。
TypeError: 'class Meta' got invalid attribute(s): sale_price,get_absolute_url.
以下是我的代码。
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('catalog_product', (), {'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
感谢。
推荐答案
你误解了模型的定义。您将方法和属性添加到实际的模型
类中,并使用 Meta
类来指定类上的选项: / p>
You are misunderstanding how models are defined. You add your methods and attributes to the actual Model
class and use the Meta
class to specify options upon the class:
class MyModel(models.Model):
old_price = ...
price = ...
slug = ...
created_at = ...
...
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('catalog_product', (), {'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
db_table = 'products'
ordering = ['-created_at']
编辑
另外,不要使用 permalink
装饰器,因为它不再被推荐:
Also, don't use the permalink
decorator as it's no longer recommended:
https://docs.djangoproject。 com / en / 1.6 / ref / models / instances /#the-permalink-decorator
永久装饰器不再推荐的。您应该在get_absolute_url方法的正文中使用reverse()。
The permalink decorator is no longer recommended. You should use reverse() in the body of your get_absolute_url method instead.
这篇关于类元获得无效属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!