gpt4 book ai didi

django - 类元获得无效属性

转载 作者:行者123 更新时间:2023-12-02 07:27:19 24 4
gpt4 key购买 nike

请帮助修复这个 Meta 类的值,因为我在详细研究后放弃了。
尝试使用“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

谢谢。

最佳答案

您误解了模型的定义方式。您将方法和属性添加到实际 Model类并使用 Meta类来指定类的选项:

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']

阅读 Model documentation并关注 Meta options 部分

编辑

另外,不要使用 permalink装饰器,因为不再推荐:

https://docs.djangoproject.com/en/1.6/ref/models/instances/#the-permalink-decorator

The permalink decorator is no longer recommended. You should use reverse() in the body of your get_absolute_url method instead.

关于django - 类元获得无效属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com